Using laravels Spatie/Roles is there a way to get the current users role who is logged in?
I've tried
if($this->hasRole('admin')) { //do something }
but it wont work
In your Model that uses the Spatie\Permission\Traits\HasRoles
trait, which is in most cases User
, you can call various methods for verifying or retrieving roles.
They are:
roles
hasRole
hasAnyRole
hasAllRoles
getRoleNames
For a given user,
$roles = $user->getRoleNames();// Returns a collection
{{ Auth::user()->roles->pluck('name') }}
Figured it out, for those of you out there this is how you do it.
if(Auth::user()->hasRole('my_role_name'))
{
// do something
}
//otherwise do something else
If you know that the user has only one role (for example: "customer") then you can have this displayed as follows:
{{ Auth::user()->roles->pluck('name')[0] ?? '' }}
// or with the auth() helper:
{{ auth()->user()->roles->pluck('name')[0] ?? '' }}
// output: "customer"
Then you can check in your blade File:
@if ( auth()->user()->roles->pluck('name')[0] ?? '' === 'customer' )
<h1>Hello Customer {{auth()->user()->name }}</h1>
...
@endif
Or even much simpler:
@role('customer')
I am a Customer!
@else
I am not a Customer ...
@endrole
Using Laravel 9 and Spatie v5 you can use
Controller
if(auth()->user()->hasRole('name')){}
Blade
@role('name')
Using laravel8 and spattie 5.5
If users only HAVE ONE ROLE; you can use:
auth()->user()->roles->pluck("id")->first()
to get the role id for the current logged user, optionally can use:
auth()->user()->roles->pluck("name")->first();
to get the role's name
Auth::user()->getRoleNames();
This will return a collection with all the roles the user has attached to.