Search code examples
laravellaravel-permission

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?


Solution

  • You can apply assignRole() on a model instance, not a builder :

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