Try something like this:
$user = User::with('roles');
$admins = $user->roles()->where('role_name', 'admin')->get();
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I'm having a really hard time getting only users with certain roles. I've tried everything I can think of and I cannot for the life of me understand this.
Get's all the users and their roles with no problem
public function show()
{
$user = User::with('roles')->get();
return $user;
}
public function show(User $user)
{
$user = User::with('roles')->get();
if($user->hasRole('admin')){
return $user;
}
}
The above gives: Call to undefined method Illuminate\Database\Eloquent\Collection::hasRole()
Other than all the above, I've tried many different ways and just can't understand it.
Please or to participate in this conversation.