php – How to assign role to user in laravel's Seeder-ThrowExceptions

Exception or error:

How to add the role “Admin” after creating a new user in AdminUserSeeder?
My insert AdminUserSeeder’s code :

<?php

use Illuminate\Database\Seeder;
use App\User;
use Spatie\Permission\Traits\HasRoles;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

class CreateAdminUserSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $user = User::create([
            'username' => 'admin', 
            'email' => 'admin@test.com',
            'password' => bcrypt('password')
        ]);

        $role = Role::create(['name' => 'Admin']);

        $permissions = Permission::pluck('id','id')->all();

        $role->syncPermissions($permissions);

        $user->assignRole([$role->id]);
    }
}

I keep getting this error when I run seeder:

BadMethodCallException : Call to undefined method
App\User::assignRole()
Illuminate\Database\Eloquent\Model::throwBadMethodCallException(“assignRole”)

How to solve:

assign role by name

    $role = Role::create(['name' => 'Admin']);

    $permissions = Permission::pluck('id','id')->all();

    $role->syncPermissions($permissions);

    $user->assignRole($role->name]);

and your model should be like this

use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use HasRoles;

    // ... etc
}

Leave a Reply

Your email address will not be published. Required fields are marked *