How To Retrieve All Related Models In A Many To Many Relationship Laravel?

- 1 answer

I am trying to retrieve all related models with another model through an intermediary table but can't figure out how. The Laravel docs say you can do something like this:

$roles = App\User::find(1)->roles()->orderBy('name')->get();

But when I try to apply that to my code

$roles = User::where('id', $user->id)->roles()->get();

It does not work. I am accepting the user model through my controller, so I do have access to it.

The relationship is also defined like so:


public function roles()
    return $this->belongsToMany(Role::class);


public function users()
    return $this->belongsToMany(User::class);

How can I get all of the roles associated with a particular user?

edit/update: I know I can simply use a foreach loop and get all of the roles associated with a particular user, but I am trying to return a resource collection, so I cannot do it that way



Try this, I am assuming that $user_id is the parameter which is passed into the controller from the URL,


But before running the above code, I assume that you have created the pivot table for many to many relationship with columns user_id and role_id. And have named the pivot table as role_user.

Hope this works