Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

moazam's avatar

Exclude roles

This is simple but I can't get it working. I am trying to get all users which don't have role admin. Here is my code:

$users = User::with(['roles' => function ($query) {
    $query->where('slug', '<>', 'admin');

}])->paginate( 15 );

When I get the query I see this:

select `roles`.*, `role_user`.`user_id` as `pivot_user_id`, `role_user`.`role_id` as `pivot_role_id`, `role_user`.`created_at` as `pivot_created_at`, `role_user`.`updated_at` as `pivot_updated_at` from `roles` inner join `role_user` on `roles`.`id` = `role_user`.`role_id` where `role_user`.`user_id` in (1, 4, 7, 11) and `slug` <> admin)
0 likes
4 replies
Jaytee's avatar
$query->where('slug', '!=', 'admin');

Would that work? 
moazam's avatar
moazam
OP
Best Answer
Level 2

So this code is working fine I am wondering what's wrong with the above code?

$users = User::whereHas('roles', function($q){
    $q->where('slug', '<>', 'admin');
})->paginate( 15 );
Ricardo's avatar

@moazam 'cause in the first one it says: give me the users. Please include roles different from admin.

In the second one it says: give me the users that has roles different from admin.

1 like

Please or to participate in this conversation.