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
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:
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?->getRoles() on $user will run this package's functions to do the actual retrieval, instead of writing your own bespoke code to query thingsThis 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()
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() );