Eloquent many-to-many-to-many – how to load distant relation easily

This is how you can do it:

User::where('id', $id)->with(['groups.permissions' => function ($q) use (&$permissions) {
     $permissions = $q->get()->unique();
}])->first();

// then
$permissions; // collection of unique permissions of the user with id = $id

Leave a Comment