0
votes

I have 3 tables: User, Role and the pivot table RoleUser with role_id and user_id.

For the relations in my models i did that :

Role Model :

   public function users() {
    return $this->belongsToMany('App\Models\User')->using(RoleUser::class);
}

User Model:

 public function roles() {
    return $this->hasMany('App\Models\Role')->using(RoleUser::class);
}

I did that for filter by one role and it works well :

 $roles = Role::find($request->get('role_id'))->first();

 return $roles->users;

But now i need to filter my users by many roles.

I ll send an array from my front-end with id's of the roles.

Actually i'm able to get the roles like below

$roles = Role::whereIn('id', $request->get('role_id'))->get();


 $roles = [{"id":2,"name":"Admin","description":"blabla","created_at":"2018-12-04 09:48:56","updated_at":"2021-04-23 14:53:15"},{"id":3,"name":"developper","description":"blabla","created_at":"2018-12-04 09:51:31","updated_at":"2021-04-23 14:53:15"}]

But i dont know how can i get the users with this roles.

1
Please note that a many-to-many, using the belongsToMany() method, should use that method for both models User and Role. You currently have hasMany() on the User model, but that should be belongsToMany(). - Tim Lewis

1 Answers

1
votes

You need to go through the collection and get each role's users and return them in one array as shown below:

$roles = Role::whereIn('id', $request->get('role_id'))->get();
return $roles->map->users->flatten();

Or you do it the other way round:

return User::whereHas('roles', function($q) use($request) {
    $q->whereIn('id', $request->get('role_id'));
})->get();