Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Spatie Roles get current users role

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

like image 675
Exploit Avatar asked Aug 19 '19 22:08

Exploit


Video Answer


3 Answers

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.

like image 166
Augusto Moura Avatar answered Nov 15 '22 10:11

Augusto Moura


{{ Auth::user()->roles->pluck('name') }}
like image 26
Endee Avatar answered Nov 15 '22 11:11

Endee


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
like image 24
Exploit Avatar answered Nov 15 '22 11:11

Exploit