Search code examples
laravellaravel-permission

How can I search for a user who has 2 roles with Spatie Laravel-permission?


I'm working with Laravel, currently I'm only focused on permissions and I need to validate that if a user has the role of Seller and Administrator they will list all the sellers, in case they don't, just list a project.

I've tried to create my own functions but I always fall into True and only allow me to validate 1 role no more

public function isSeller(){

  foreach (Auth::user()->getRoleNames() as $role) {
     if ($role == 'vendedor') {
          return true;
     } else {
          return false;
     }
  }
}

If in the previous query within if I put && $role == 'admin' it will always return true even if the user does not have the role.


Solution

  • You can directly check as given below, it will return true if user has role seller or admin

    Auth::user()->hasRole('seller','admin')
    

    If you want to check user has both roles then

    Auth::user()->hasAllRoles('seller','admin')