Laravel-permission: How to retrieve particular user roles?

Created on 24 Aug 2018  路  5Comments  路  Source: spatie/laravel-permission

I have got user roles by using this getRoleNames() but i need to get particular user role.
for example user1 has student, volunteer, admin these roles
i want to get user roles other than student ie admin and volunteer roles only

support

Most helpful comment

This retrieves the assigned roles to the current logged in user, plucks the role name and converts to an array

dd(Auth::user() ->roles ->pluck('name') ->toArray() );

All 5 comments

You can get a collection of all roles assigned to a user via $user->roles relation. Then filter out the ones you aren't interested in.

This doesn't work for me.

       $user = User::find($id);

        dd($user->roles);

the dump is empty, despite the user having an assigned role.

@paulcanning wrote:

the dump is empty, despite the user having an assigned role.

Without more context of your app and how you are running that code, it's hard to give a concrete answer. Lots of unknowns when trying to respond to 2 lines of code.

Things to consider:

  • maybe the cache is outdated because you assigned the role with bespoke code instead of calling the provided functions
  • while your example shows an immediate dd() call after querying the User, if you're actually also doing other things in between the lines of code you quoted, maybe the retrieved object needs a ->fresh() call against it to retrieve assignments you've done in the meantime?
  • calling ->getRoles() on $user will run this package's functions to do the actual retrieval, instead of writing your own bespoke code to query things

This retrieves the assigned roles to the current logged in user, plucks the role name and converts to an array

dd(Auth::user() ->roles ->pluck('name') ->toArray() );

Further filter:
Auth::user()->roles->where("name","parent")->pluck('id')->toArray()

Was this page helpful?
0 / 5 - 0 ratings

Related issues

devingray picture devingray  路  3Comments

ionesculiviucristian picture ionesculiviucristian  路  4Comments

hosseinnedaei picture hosseinnedaei  路  3Comments

bbdangar picture bbdangar  路  4Comments

NattananWs picture NattananWs  路  3Comments