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

LaraBABA's avatar

Problems filtering role names

Hi all,

I am trying to pluck 2 columns but filtering the results based on roles. It does not seem to be doing anything. I get all the results but unfiltered.

Any idea how to plug using ->hasAnyRole(['super-admin', 'manager']) please?

        $users = User::pluck('email', 'id')->hasAnyRole(['super-admin', 'manager']);

        return view('app.gamess.create', compact('users'));

Thank you

0 likes
5 replies
s4muel's avatar

does this work like you want?

$users = User::hasAnyRole(['super-admin', 'manager'])->pluck('email', 'id');

edit: oh, since you didnt write show us your hasAnyRole() method, i assume now, do you use the spatie permissions package? if so, it has a scope to query only certain roles.

have a look at: https://spatie.be/docs/laravel-permission/v5/basic-usage/basic-usage relevant part:

$users = User::role('writer')->get(); // Returns only users with the role 'writer'
The role scope can accept a string, a \Spatie\Permission\Models\Role object or an \Illuminate\Support\Collection object.
2 likes
LaraBABA's avatar

@s4muel Thanks for your help, this was the right answer(from @tykus ):

$users = User::role(['super-admin', 'manager'])->pluck('email', 'id'); 
tykus's avatar
tykus
Best Answer
Level 104

You get a Collection from pluck; so this is not what you need. Instead, consider the role scope which should allow you to scope the User query correctly (assuming the User model uses the HasRoles trait

$users = User::role(['super-admin', 'manager'])->pluck('email', 'id');

@samuel the hasAnyRole method is not a scope; so that will not work.

2 likes

Please or to participate in this conversation.