Home > Software design >  laravel spatie permission hasPermissionTo not work with string
laravel spatie permission hasPermissionTo not work with string

Time:05-18

I want to test a feature in which the user checks to have this permission for the operation. When I pass a Permission model it returns a good result, but when I giv the the permission name in a parameter it runs an error.

composer.json

"laravel/framework": "^9.3",
"spatie/laravel-permission": "^5.5"  

Test.php

$permission = 'do-something';
$permissionModel = Permission::create([
   'name' => $permission,
   'guard_name' => 'sanctum'
]);

$user = User::factory()->create();
$user->givePermissionTo($permissionModel);

$user->hasPermissionTo($permissionModel); // return true
$user->hasPermissionTo($permission); // fail with error:
Spatie\Permission\Exceptions\PermissionDoesNotExist: There is no permission named `do-something` for guard `sanctum`.

I want to use the string solution, what am I doing wrong?

CodePudding user response:

If the permission name is exist in your permissiom table then try the following command:

php artisan cache:forget spatie.permission.cache

Then

php artisan cache:clear
  • Related