@mrkarma4ya Did you add the HasRoles trait to your User model (i.e. use HasRoles)?
Jan 27, 2021
4
Level 3
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() .
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.