Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel spatie assign role to user not working

I am simply doing what is in the documentation but God knows what the issue is. I have put use HasRoles; in my User Model

use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable implements JWTSubject
{
    use HasRoles;
}

but again and again, getting this error:

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

Whenever assigning role in seeder:

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

  public function run()
  {
     $role = Role::where('name', 'Admin')->first();
     $user = User::where(['email' => '[email protected]', 'password' => 'password']);
     $user->assignRole($role);
  }

givePermissionTo is also throwing same sort of error. Any idea why this error is coming?

like image 721
Maha Waqar Avatar asked Oct 31 '25 20:10

Maha Waqar


1 Answers

Add trait use HasRoles; in your user model.

Import it with use Spatie\Permission\Traits\HasRoles; at the top of the user model file.

like image 57
Muhammad Ibrahim Avatar answered Nov 03 '25 09:11

Muhammad Ibrahim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!