joun
joun

Reputation: 664

How to check multiple permission condition in if statement using laravel spatie package?

I need to check condition in if statement for multiple permissions. It is using spatie package from laravel. I use this code below but it seems doesn't work. It can display the output but the output is not correct. It doesn't filter the condition.

if (auth()->user()->can('View Consultant') || auth()->user()('View Administration') 
|| auth()->user()('View Accountant') || auth()->user()('All departments')) 
 {

        $itemregistrations = DB::table('itemregistrations')
                             ->where('categoryid','=', '1',',','2',',','3')
                             ->get();

        return view('profil.index', compact('itemregistrations'));

 } 

Is the code is correct?

The condition is the users with permission (view consultant, view administration, view accountant, all departments) can view list of consultant, administration and accountant from all departments.

For users with permission(view consultant only) can only view consultant list.

Upvotes: 1

Views: 7825

Answers (4)

topher
topher

Reputation: 1397

@can blade directive accepts an array of permissions, the result is the same as ->hasAllPermissions

@can(['user create', 'user edit'])
    ...
@endcan

Also there's another blade directive called @canany, the result is the same as ->hasAnyPermission

@canany(['user create', 'user edit'])
    ...
@endcanany

Tested on these versions:

laravel/framework 8.83.5
spatie/laravel-permission 3.18.0

Upvotes: 8

ufuk
ufuk

Reputation: 371

Can be used in 2 ways. Single control is as follows.

@can('edit articles')
  //
@endcan

Multiple control is as follows.

@if(auth()->user()->can('edit articles') && auth()->user()->can('edit uploads'))
  //
@endif

Upvotes: 1

Serhii Posternak
Serhii Posternak

Reputation: 504

If you need to check that the model has all the permissions, you should use method hasAllPermissions(). For example:

if (\Auth::user()->hasAllPermissions('View Consultant', 'View Administration', 'View Accountant', 'All departments')) {
    // do something
} 

Upvotes: 1

Vijay Rana
Vijay Rana

Reputation: 1079

According to the documentation,

You can check if a user has Any of an array of permissions:

$user->hasAnyPermission(['edit articles', 'publish articles', 'unpublish articles']);

So, you can do the following to check for multiple condition.

if (auth()->user()->hasAnyPermission(['View Consultant', 'View Administration', 'View Accountant', 'All departments']) 
 {
        $itemregistrations = DB::table('itemregistrations')
                             ->where('categoryid','=', '1',',','2',',','3')
                             ->get();

        return view('profil.index', compact('itemregistrations'));

 } 

Upvotes: 3

Related Questions