Reputation: 15027
I have a user model with pivot table role_user.
In my user table I have a field 'active'.
And a user can have multiple roles which are saved in pivot table.
How can I pull all the users where active = 1 and where user has specific role in pivot table?
Upvotes: 1
Views: 526
Reputation: 163748
To filter users by role use whereHas()
method:
User::whereHas('roles', function($q) use ($role) {
$q->where('role', $role);
})->where('active', 1)->get();
Upvotes: 3
Reputation: 1686
Try this. This assumes you have an eloquent relationship set up between users and roles. I've only used this type of query in a hasMany
/ belongsTo
relationship, but I think it'll work in your example as well.
$users = User::where('active', 1)->whereHas('roles', function ($query) {
$query->where('role', 'foo');
})->get();
Upvotes: 4