0

I'm relatively new to Laravel and I'm try to learn spatie/laravel-permission. I'm using Laravel 10. I'm trying to seed my database with roles and a user.

I'm getting this error:
Spatie\Permission\Exceptions\RoleDoesNotExist There is no role named admin.

Here is my code. As you can see in the RoleSeeder I do create an admin role. I also have the HasRoles trait in the User model. I'm not sure what I'm doing wrong. Any help would be greatly appreciated.

RoleSeeder.php

<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Role;

class RoleSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        Role::create(['name' => 'super admin', 'team_id' => 1, 'guard_name' => 'web']);
        Role::create(['name' => 'admin', 'team_id' => 1, 'guard_name' => 'web']);
        Role::create(['name' => 'user', 'team_id' => 1, 'guard_name' => 'web']);
    }
}

AdminSeeder.php

<?php

namespace Database\Seeders;

use App\Models\User;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class AdminSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $user = User::create( [
            'name' => 'admin',
            'email' => 'admin@gmail.com',
            'email_verified_at' => now(),
            'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
        ]);
        $user->assignRole('admin');
    }
}

DatabaseSeeder.php

<?php

namespace Database\Seeders;

// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

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

User.php

<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable, HasRoles;

    protected $guard_name = 'web';

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
    ];
    
}
Fly_Moe
  • 239
  • 1
  • 2
  • 11
  • id you run the seed command ? – N69S Jun 27 '23 at 23:04
  • Yes. These are the commands I ran: `php artisan optimize:clear` and `php artisan migrate:fresh --seed` – Fly_Moe Jun 27 '23 at 23:17
  • Are you sure that team_id has to be 1? You can try setting it to null in the seeder to create a global role – Pippo Jun 28 '23 at 02:45
  • @Pippo I set them all to null and got this error: `SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'team_id' cannot be null (Connection: mysql, SQL: insert into "model_has_roles" ("model_id", "model_type", "role_id", "team_id") values (1, App\Models\User, 2, ?))` That's why I added 1 to it, just to give it a default value. – Fly_Moe Jun 28 '23 at 02:55
  • This is the official documentation: https://spatie.be/docs/laravel-permission/v5/basic-usage/teams-permissions#content-roles-creating – Pippo Jun 28 '23 at 03:02
  • @Pippo Yep, I've tried following the documentation and it's not working for me. I'm missing something I guess? – Fly_Moe Jun 28 '23 at 03:17

1 Answers1

0

After several hours of researching, I finally figured it out. Hope this helps someone.

According to the Spatie documentation setPermissionsTeamId needs to be set if using teams, which I am using. Once teams are active you have to work one team at a time. This isn't really clear in the documentation, at least to me.

After setting the TeamId, I had to grab the role object and then assign it in the assignRole() method. Looks like I was trying to assign it by string before which wasn't working.

AdminSeeder.php

<?php

namespace Database\Seeders;

use App\Models\User;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Role;

class AdminSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $user = User::create( [
            'name' => 'admin',
            'email' => 'admin@gmail.com',
            'email_verified_at' => now(),
            'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
        ]);

        // Set TeamId
        setPermissionsTeamId(1);

        // Get Role object, then assign it 
        $role = Role::findByName('admin','web');
        $user->assignRole($role);
    }
}
Fly_Moe
  • 239
  • 1
  • 2
  • 11