Maha Waqar
Maha Waqar

Reputation: 643

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?

Upvotes: 4

Views: 11660

Answers (3)

FreeStyler
FreeStyler

Reputation: 317

Had almost same error, but it's sounds like

Call to undefined method App\Models\User::assignRole()

Like Muhammad Ibrahim wrote, I added HasRoles trait and it works! Below code for clue

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;

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

Upvotes: 0

Muhammad Ibrahim
Muhammad Ibrahim

Reputation: 557

Add trait use HasRoles; in your user model.

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

Upvotes: 3

STA
STA

Reputation: 34678

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);
}

Upvotes: 2

Related Questions