Laravel Spatie Roles get current users role

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

Usage example

For a given user,

$roles = $user->getRoleNames();// Returns a collection

Reference here.


{{ 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