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

luddinus's avatar

Get user with explicit roles

Hi.

Imagine I have two roles: editor and admin

I want to fetch those users which are ONLY editors (admins are editors too).

So, this is what I'm trying, but it fetchs admins too...

$editors = User::whereHas('roles', function($roles) {
   return $roles->whereName('editor');
})->get();

What would be the query I'm looking for?

0 likes
2 replies
InaniELHoussain's avatar

what about. $editors = User::whereHas('roles', function($roles) { return $roles->where('name', '=', 'editor'); })->get();

luddinus's avatar

@AkiyamaSmart That's the same query.

Using that, it does not get only editors, it will get admins too. (because an admin is an editor too).

Probably it is no the best example, what I want is to get the users where has only that specific rules, not all those "includes" that rules and have more.

Please or to participate in this conversation.