There is no role named `admin`. laravel

Viewed 10261

i use this package :

https://github.com/spatie/laravel-permission/tree/v2

code :

     $user=User::find(2);
    $user->assignRole('admin');

and when i assign admin role to user I'm dealing with this error

There is no role named admin.Spatie\Permission\Exceptions\RoleDoesNotExist

this is my default guard in auth.php :

    <?php

return [

    'defaults' => [
        'guard' => 'api',
        'passwords' => 'users',
    ],


    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
            'hash' => false,
        ],
    ],

this is my roles table :

enter image description here

this is my role_has_permission table

enter image description here

and this is my permission table :

enter image description here

6 Answers

just add this protected property to your user model(or whatever model you are using for assigning permissions and roles).

protected $guard_name = 'api';

Add this to your user model

use Spatie\Permission\Traits\HasRoles;

and in a user model class

use HasRoles;

Here is a reference

Complete example

Add one of the following to your User model:

public $guard_name = 'api';

Or:

public function guardName()
{
  return 'api';
}

As a convention it's best to do configurable things in the config file.
The problem with your code is the order of arranging your guards, just re-arrange as seen below.

<?php

return [

    'defaults' => [
        'guard' => 'api',
        'passwords' => 'users',
    ],


    'guards' => [
        'api' => [
            'driver' => 'token',
            'provider' => 'users',
            'hash' => false,
        ],
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
    ],
 ...

Once this is done, you don’t need to add protected $guard_name = 'api'; to your User model, ensure to run php artisan config:clear

Ref: Saptie Laravel Permisions

friends! I found solution for this problem but first of all, i illustrate why this problem happened. As you know, Laravel read the codes from top to bottom and from left to right. Moreover when we want from laravel fresh all data by command

php artisan migrate :fresh --seed

It clears all this data and the problem begin. By other word, when assign Role command to check for new role it fails because all data is cleared before it access to those data. To avoid this we should set Role seeder class before Admin seeder class in database seeder

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
       $this->call([RoleSeeder::class, AdminSeeder::class]);
    }
}

This worked for me:

$role = Role::create(['guard_name' => 'admin', 'name' => 'manager']);
Related