Exploit
Exploit

Reputation: 6386

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

Upvotes: 17

Views: 87257

Answers (8)

Tasfir Hossain
Tasfir Hossain

Reputation: 61

I getting the current loged in Admin user name using

$user->getRoleNames()->first();

And getting the response is

"Super Admin"

Upvotes: 6

dennis-main
dennis-main

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

Sekuestran
Sekuestran

Reputation: 41

Using Laravel 9 and Spatie v5 you can use

Controller

if(auth()->user()->hasRole('name')){}

Blade

@role('name')

Upvotes: 4

Rafael Otamendi
Rafael Otamendi

Reputation: 21

Auth::user()->getRoleNames();

This will return a collection with all the roles the user has attached to.

Upvotes: 0

Augusto Moura
Augusto Moura

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

Usage example

For a given user,

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

Reference here.

Upvotes: 29

Maik Lowrey
Maik Lowrey

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

Endee
Endee

Reputation: 181

{{ Auth::user()->roles->pluck('name') }}

Upvotes: 18

Exploit
Exploit

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

Related Questions