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

codetycon's avatar

How to get an All users who have an certain role?

I have three roles: 1. Admin 2. Client 3. Store

I have three tables: 1. users 2. roles 3.role_users

How can I get all users who have a role Client

I tried this

$clients = User::all()->where('App\Models\Role',Role::CLIENT);
0 likes
1 reply
codetycon's avatar
codetycon
OP
Best Answer
Level 1

You can do it with whereHas() method. it's a way to condition on relation using exists in query

$clients = User::whereHas('roles', function($role) {
    $role->where('name', '=', Role::CLIENT);
})->get();

If you want to get the role too, stack the with() method

$clients = User::whereHas('roles', function($role) {
    $role->where('name', '=', Role::CLIENT);
})->with(['roles' => function($role) {
    $role->where('name', '=', Role::CLIENT);
}])->get();```

Please or to participate in this conversation.