Reputation: 6386
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
Upvotes: 17
Views: 87257
Reputation: 61
I getting the current loged in Admin user name using
$user->getRoleNames()->first();
And getting the response is
"Super Admin"
Upvotes: 6
Reputation: 41
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
Upvotes: 2
Reputation: 41
Using Laravel 9 and Spatie v5 you can use
Controller
if(auth()->user()->hasRole('name')){}
Blade
@role('name')
Upvotes: 4
Reputation: 21
Auth::user()->getRoleNames();
This will return a collection with all the roles the user has attached to.
Upvotes: 0
Reputation: 1427
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
Upvotes: 29
Reputation: 17594
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
Upvotes: 12
Reputation: 6386
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
Upvotes: 8