Reputation: 7302
I'm setting up a REST API using Laravel 5.7. To validate authentication I JWT-auth and for permissions and roles I use Spatie.
My problem: when trying to link a role to a user I get the following error
Spatie \ Permission \ Exceptions \ RoleDoesNotExist
There is no role named admin.
The role do exist in the database:
This is how I'm trying to assign a role to the user:
$user = User::findOrFail(1);
$user->assignRole('admin');
As I'm new to Laravel I'm not sure if it's relevant, but setting the JWT I had to change the driver of the guard in the config/auth.php
to jwt
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
I can't see what I'm doing wrong. I added the roles and then tried to add the role to a user.
Upvotes: 4
Views: 6355
Reputation: 900
If none of other answers solved your problem
Check that you are using queue if so restart the queue
Upvotes: 0
Reputation: 377
Guard has been changed from the web to api but still try to find web from the database assign a role like this.
$roleToAssign = Role:: findByName('administrator', 'api');
$user->assignRole($roleToAssign);
Upvotes: 0
Reputation: 10447
I'm assuming you've manually added the roles to the database. The roles are cached and it causes issues if you don't use the built in create methods.
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
$role = Role::create(['name' => 'writer']);
$permission = Permission::create(['name' => 'edit articles']);
You will need to manually clear the cache with php artisan cache:clear
.
The better way to do this is either to use a seeder (for permanent roles) or Tinker to run the code to create roles and permissions, which will trigger the cache to be cleared.
Upvotes: 0
Reputation: 788
Check your app namespace. If you updated it from App
, be sure to update it in config/auth.php
.
On the other hand, if you didn't update the App
namespace, try clearing your cache and re-seed the database tables.
php artisan config:cache
php artisan cache:clear
Also check the user model if you have protected $guard_name = 'api';
in there.
Hope this helps. Cheers!
Upvotes: 5