Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mrkarma4ya's avatar

Assign Roles to Users while seeding [Spatie Roles and Permissions package]]

I want to assign Roles to Users while seeding, but I'm getting this error:

Call to undefined method Illuminate\Database\Eloquent\Builder::assignRole()

My Seeder Class:

<?php

namespace Database\Seeders;

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

class RolesAndPermissionsSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // Reset cached roles and permissions
        app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();

        // Create Permissions
        Permission::create(['name' => 'do anything']);
        Permission::create(['name' => 'administer website']);

        // Create roles and assign created permissions
        $role = Role::create(['name' => 'super-admin']);
        $role->givePermissionTo(Permission::all());

        $role = Role::create(['name' => 'admin']);
        $role->givePermissionTo('administer website');

        

        // Assign roles to demo users
        $superadmin = User::where('id',1)->get();

        $superadmin->assignRole('super-admin');

        $admin = User::where('id',2)->get();
        $admin->assignRole('admin');


    }
}

Also, how can I dump $superadmin or $admin to check if they are being retrieved correctly? I'm using the terminal to run migration, so I can't do dd() .

0 likes
4 replies
mrkarma4ya's avatar

Yes

use Spatie\Permission\Traits\HasRoles;

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

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
CorvS's avatar
CorvS
Best Answer
Level 27

@mrkarma4ya You are querying multiple admins with ->get(), so $superadmin is a collection. If you want a single user do User::find(1) or use ->first(). Additionally you are still able to use dd in your seeder, the dump is gonna be visible in your terminal then.

1 like

Please or to participate in this conversation.