skip to Main Content

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


  1. It’s usually cache issue in the package. Try clearing cache (php artisan cache:clear) and let the package handle the caching.

    Login or Signup to reply.
  2. I advise you to:

    • check defined permissions with php artisan permission:show

    • check users permisions using php artisan tinkerand 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

    Login or Signup to reply.
  3. Pode limpar o cache utilizando o comando:

     app()->make(SpatiePermissionPermissionRegistrar::class)->forgetCachedPermissions();
    app()->make(SpatiePermissionPermissionRegistrar::class)->clearClassPermissions();
               app()->make(SpatiePermissionPermissionRegistrar::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 SpatiePermissionTraitsHasRoles;
    class Usuario extends  Authenticatable
    {
        use HasRoles;
    

    Pode verificar a permissão do usuário com:

    auth()->user()->can('View Country')
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search