TheAkashRajput TheAkashRajput - 1 year ago 140
PHP Question

How to chain eloquent relations in laravel?

So far I was extracting the relation objects as arrays and then doing something like:


But however is there a way to do something like:


It works until
but no further chaining. Please help if you've done something. Or I'm just newbie.

Answer Source

You could use eager loading to load the user's group and then load all of the members of that group.

$user = User::with(['group', 'group.members'])->find(1);

// OR if you already have a user object (Like when using the Auth facade)
$user = Auth::user()->load(['group', 'group.members']);

foreach ($user->group->members as $member) {
    // Do something with a member

However, if you essentially want to jump down the structure a level, and get all the members related to a user, you could use the hasManyThrough relationship, in that a user has many members, through a group.

// In your User model
public function members()
    return $this->hasManyThrough(Member::class, Group::class);

That way you can simply access the members directly through the user:

$members = Auth::user()->members;

Instead of doing a query to access the user's group and then doing another query to access that group's members, Laravel would use a single query with a join to get you the members.

Take a look at the hasManyThrough relationship here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download