when using laravel spatie permissions every thing is ok when creating permissions , roles , assign roles to users.
but when using $this->authorize('View Country')
OR $user->can('View Country')
always return true
.
i am using laravel v9.0 and spatie/permissions v5.5
and tried some solutions like :
- upgrade spatie/permissions to v6.0
- running
php artisan optimize
but noting happen
assign role to user:
$user = Admin::findOrFail(request('user_id'));
$role = Role::findOrFail(request('role_id'));
$user->syncRoles([$role->name]);
return redirect()->route('admin.admins.index')->with('success', __(" Successfully"));
create role permissions and sync
$role = Role::find(request('role_id', 1));
foreach ($request->permissions as $permisssion) {
$permisssions[] = Permission::firstOrCreate([
'name' => $permisssion,
'guard_name' => 'admin'
]);
}
$role->syncPermissions($permisssions ?? []);
3
Answers
It’s usually cache issue in the package. Try clearing cache (
php artisan cache:clear
) and let the package handle the caching.I advise you to:
check defined permissions with
php artisan permission:show
check users permisions using
php artisan tinker
and entering a commanad like:User::where('id', '<', 11)->get()->map(fn ($user) => [[$user->id, $user->name], $user->getAllPermissions()->pluck ('name')->toArray()])
(customize the where condition as your needings)check if you have defined a Custom Permission, finding in your code ‘Gate::before’ (tipically is set in boot method of app/Providers/AuthServiceProvider.php) – look here and here for reference
Pode limpar o cache utilizando o comando:
Para criar e vincular as permissões:
No model User deve chamar
Pode verificar a permissão do usuário com: