Reputation: 14218
users
id
roles
id
name
user_roles
user_id
role_id
I would like to query all users with specific roles. e.g. get all users that have the role 'admin'
Upvotes: 2
Views: 51
Reputation: 50491
There is also the option to go at the relationship from the other direction:
Role::where('name', 'admin')->firstOrFail()->users;
Upvotes: 2
Reputation: 163768
If you know role ID, do this:
User::whereHas('roles', function ($q) use($roleId) {
$q->where('id', $roleId);
})
->get();
If you know only name or title of the role, do this:
User::whereHas('roles', function ($q) use($roleTitle) {
$q->where('title', $roleTitle);
})
->get();
Upvotes: 1
Reputation: 1006
So, you can use the whereHas from Eloquent
$users = User::whereHas('roles', function($query) {
$query->where('name', 'admin');
})->get();
See here for reference https://laravel.com/docs/5.5/eloquent-relationships
Upvotes: 2