4
votes

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.

4
Have you installed all the packages ?Akhtar Munir
@AkhtarMunir yes, all packages, all the stepsAndré Luiz
Spatie is the developer btw. The package is laravel-permissionsDerek Pollard
I only bring this up because Spatie is a rather popular company that does open source development, especially with various laravel packagesDerek Pollard
Did you manually add those roles to the database?Styphon

4 Answers

5
votes

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!

0
votes

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.

0
votes

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

0
votes

If none of other answers solved your problem

Check that you are using queue if so restart the queue