Reputation: 664
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
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
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
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
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