Reputation: 171
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 :
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 ?? []);
Upvotes: 2
Views: 1419
Reputation: 1
Pode limpar o cache utilizando o comando:
app()->make(\Spatie\Permission\PermissionRegistrar::class)->forgetCachedPermissions();
app()->make(\Spatie\Permission\PermissionRegistrar::class)->clearClassPermissions();
app()->make(\Spatie\Permission\PermissionRegistrar::class)->registerPermissions();
Para criar e vincular as permissões:
foreach ($permissoes as $permissao) {
$permission = Permission::create($permissao);
$role->givePermissionTo($permission);
}
No model User deve chamar
use Spatie\Permission\Traits\HasRoles;
class Usuario extends Authenticatable
{
use HasRoles;
Pode verificar a permissão do usuário com:
auth()->user()->can('View Country')
Upvotes: 0
Reputation: 5309
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
Upvotes: 3
Reputation: 31
It's usually cache issue in the package. Try clearing cache (php artisan cache:clear
) and let the package handle the caching.
Upvotes: 1