0
votes

I need help for my Laravel application.

I use spatie roles and permissions.

When i create the user, assign roles is no problem. When i will update the same user, there is the following error:

[2019-12-06 08:44:36] local.ERROR: The given role or permission should use guard instead of `web`. {"userId":1,"exception":"[object] (Spatie\\Permission\\Exceptions\\GuardDoesNotMatch(code: 0): The given role or permission should use guard instead of web. at /home/vagrant/code/test/vendor/spatie/laravel-permission/src/Exceptions/GuardDoesNotMatch.php:12)

public function store(StoreUserRequest $request)
{
    $user = $this->repo->create( $request->all());

    $user->assignRole($request->roles);

    return $user;
}

public function update(UpdateUserRequest $request, User $user)
{
    $user = $this->repo->update($user, $request->all());

    $user->assignRole($request->roles);

    return $user;
}

I added protected $guard_name = 'web'; to the User Model but still the same problem.

What is wrong? Is there a problme with the userId?

2
this could be good if you try delete tbl models_has_roles then assignRole() again to your user DB::table('model_has_roles')->where('model_id',$id)->delete(); and assign role again $user->assignRole($request->input('roles'));Mahdi Safari

2 Answers

1
votes

On update method use syncRoles instead of assignRole

0
votes

When you assign role for a user the model path App\User insert into table model_has_roles if you change the model folders spatie give you an error. I think this code may help you more.
don't missing add HasRoles

class User extends Authenticatable
{

    use Notifiable, HasRoles;
    ...
}

make sure you import use App\User;
UserController

public function update(Request $request, $id)
    {
        $this->validate($request, [
            'name' => 'required',
            'email' => 'required|email|unique:users,email,'.$id,
            'password' => 'same:confirm-password',
            'roles' => 'required'
        ]);


        $input = $request->all();
        if(!empty($input['password'])){ 
            $input['password'] = Hash::make($input['password']);
        }else{
            $input = array_except($input,array('password'));    
        }


        $user = User::find($id);
        $user->update($input);
        DB::table('model_has_roles')->where('model_id',$id)->delete();


        $user->assignRole($request->input('roles'));


        return redirect()->route('users.index')
                        ->with('success','User updated successfully');
    }