Search code examples
phplaraveleloquent

Laravel Eloquent and combing data to send to View


I'm trying to figure out a way to combine data from two tables into a single variable that I can then send to my view. I'm using Authority as my authentication bundle and so I have the following tables set up: users, roles, role_user. I want to get the following data into a single variable.

From the users table: id, name, email

From the roles table: name

The following returns all the user data in the users table:

$users = User::all(); 

But, I want to make a chain that can get the related data stored in the roles table? I want all users and all of each users roles together.

And while I can find examples that help get related data for a single record I haven't been able to find any reference to retrieving entire tables with related data.

Thanks.


Solution

  • $users = User::with('roles')->get()
    

    Eager loading is what you are looking for, read the docs :)