如何在 laravel 中插入 super_admin 播种器?

How can I insert the super_admin seeder in laravel?

SuperAdminSeeder.php

    public function run()
    {
        #Super Admin Seeder
        $role = Role::where('name', 'super_admin')->first();
        $user = User::create([
            'name' => 'Jhon Cena',
            'email' => 'jhon@gmail.com',
            'password' => Hash::make('jhoncena'),
            'remember_token' => Str::random(60),
        ]);

        $user->role()->attach($role->id);
    }

This is my SuperAdmin seeder which task is to make a user with role super_admin

DatabaseSeeder.php

    public function run()
    {

        $this->call(RegionSeeder::class);
        $this->call(CountrySeeder::class);
        $this->call(LocationSeeder::class);

        $this->call(ProductSeeder::class);
        $this->call(SliderSeeder::class);
        $this->call(BannerSeeder::class);
        $this->call(SuperAdminSeeder::class);   //this is the Super Admin seeder
        $this->call(RoleSeeder::class);
        $this->call(UserSeeder::class);
        $this->call(ShopSeeder::class);
    }

This is the database seeder

我遇到的错误 [php artisan migrate:fresh --seed]

Illuminate\Foundation\Bootstrap\HandleExceptions::handleError("Trying to get property 'id' of non-object", "E:\github\LARAVEL\Deal-Ocean\database\seeds\SuperAdminSeeder.php", [Object(App\User)])

我是新来的laravel

当您 运行 超级管理员播种者时,它导致没有 super_admin 角色。您应该在 RoleSeeder 之后添加 SuperAdmin Seeder。

public function run()
{

    $this->call(RegionSeeder::class);
    $this->call(CountrySeeder::class);
    $this->call(LocationSeeder::class);

    $this->call(ProductSeeder::class);
    $this->call(SliderSeeder::class);
    $this->call(BannerSeeder::class);
    $this->call(RoleSeeder::class); //this seeder must have superadmin role
    $this->call(SuperAdminSeeder::class);   //this is the Super Admin seeder
    $this->call(UserSeeder::class);
    $this->call(ShopSeeder::class);
}
public function run()
{

    $this->call(RegionSeeder::class);
    $this->call(CountrySeeder::class);
    $this->call(LocationSeeder::class);

    $this->call(ProductSeeder::class);
    $this->call(SliderSeeder::class);
    $this->call(BannerSeeder::class);

    $this->call(RoleSeeder::class);
    $this->call(SuperAdminSeeder::class);   //this is the Super Admin seeder

    $this->call(UserSeeder::class);
    $this->call(ShopSeeder::class);
}

Just put the RoleSeeder above the SuperAdminSeeder.

Because roles table might have a column value named super_admin. SO you must call the RoleSeeder Because there is a foreign key constriant.. And then you can insert the super admin using SuperAdminSeeder