lewis4u
lewis4u

Reputation: 15027

Laravel eloquent query model with pivot

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

Answers (2)

Alexey Mezenin
Alexey Mezenin

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

jackel414
jackel414

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

Related Questions