4

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: enter image description here

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.

apokryfos
  • 38,771
  • 9
  • 70
  • 114
André Luiz
  • 6,642
  • 9
  • 55
  • 105

4 Answers4

5

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!

petersowah
  • 728
  • 8
  • 20
0

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']);

From the GitHub docs

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.

Styphon
  • 10,304
  • 9
  • 52
  • 86
0

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);

#Link

Manmeet Khurana
  • 367
  • 2
  • 13
0

If none of other answers solved your problem

Check that you are using queue if so restart the queue

myckhel
  • 800
  • 3
  • 15
  • 29