diegoaguilar
diegoaguilar

Reputation: 8376

How should I use Laravel Eloquent queries and use relationships?

I have a User model which belongsTo a Department.

So Department got id and name fields.

At the User model I got:

public function department() {

      return $this->belongsTo('Department');
}

That way I can do something like: Auth::user()->department->name getting the actual name of the department user belongs to.

However, when I'm calling some users, I can't figure out best way to get multiple rows containing its department attribute with a name.

I wrote:

$users = User::all();
foreach ($users as $user) {
    $user -> department = Department::find($user->department_id)->name;
}

Is there a better way to do this?

Upvotes: 0

Views: 71

Answers (2)

lukasgeiter
lukasgeiter

Reputation: 153120

You can eager load related models so they are loaded for all users with only one database query and will be included in JSON output:

$users = User::with('department')->get();

More about eager loading in the Laravel Docs

Upvotes: 3

mininoz
mininoz

Reputation: 5958

It seems that you got the relationship between User Model and Department Model already. So you can call it like you did with Auth().

$users = User::all();
foreach ($users as $user) {
    echo $user->department->name ;
}

Upvotes: 1

Related Questions