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

noblemfd's avatar

How to Query Spatie Role-Permission

In my Laravel-5.8 Spatie Project. I want to query the id and name of user in users table where Spatie User Role is "Super Admin".

How do I do this?

Thank you.

0 likes
5 replies
noblemfd's avatar

I came across this:

$users = User::role('Super Admin')->get();

but don't know how to select id,name

gcwilliams's avatar

What are you trying to do exactly? Get a list of users with a specific role? Check to see if the specific user has a role?

noblemfd's avatar

I want to get the id, name of users with specific role e.g "Super Admin" role

Snapey's avatar
Snapey
Best Answer
Level 122

From the docs

$users = User::role('writer')->get(); // Returns only users with the role 'writer'

so, provided the name of the role is EXACTLY 'Super Admin' then

$users = User::role('Super Admin')->get();

$users->first()->name;
$users->first()->id;

or

$users = User::role('Super Admin')->pluck('name','id');

or 

@foreach($users as $user)
    <option value="{{ $user->id }}" >{{ $user->name }}</option>
@endforeach

Just depends how you want to use these users

Prokosa's avatar
User::select('id','name')->whereHas( 'roles', function ( $query ) use ( $role ) { $query->where( 'name', $role ); } ) ->get();

Where $role='Super Admin'

Please or to participate in this conversation.