WebDev84
WebDev84

Reputation: 331

Get all users with one role or another using Eloquent

I am trying to display a list of users with the role of 'admin' or 'webmaster'. I can get it to work when specifying only one role but when I try to get both by adding an orWhere clause it returns all of the users regardless of their role.

$admins = User::whereHas('roles', function($q) {
    $q->where('name', 'Admin');
})->paginate(25);

I've tried the following but it returns all of the users with every role.

$admins = User::whereHas('roles', function($q) {
    $q->where('name', 'Admin')
        ->orWhere('name', 'Webmaster');
})->paginate(25);

Does anybody have any ideas on how to accomplish this? For reference I have a users table, a roles table, and a role_user table that is a many-to-many from roles to users.

Upvotes: 2

Views: 506

Answers (1)

Sapnesh Naik
Sapnesh Naik

Reputation: 11636

Try this,

$admins = User::whereHas('roles', function($q) {
    $q->whereIn('name', ['Admin', 'Webmaster'] );
})->paginate(25);

Upvotes: 3

Related Questions