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.
many-to-many, using thebelongsToMany()method, should use that method for both modelsUserandRole. You currently havehasMany()on theUsermodel, but that should bebelongsToMany(). - Tim Lewis