Home > Net >  Spatie assignRole not working (Call to undefined method Illuminate\Database\Eloquent\Relations\B
Spatie assignRole not working (Call to undefined method Illuminate\Database\Eloquent\Relations\B

Time:10-22

Spatie user role permissions not working

Here is my RoleController.php

use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
public function saveUserRoles(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'role_name' => 'required|string|unique:roles,name',
        ]);
        if ($validator->fails()) {
            alert()->error(trans($validator->messages()->all()[0]));
            return back();
        }
        $role = new Role;
        $role->name = $request->role_name;
        $role->guard_name = config('auth.defaults.guard');
        $role->save();
        alert()->success(trans('New Role Created Successfully!'));
        return redirect()->route('admin.add.user.roles');
    }

User Model

User.php
use Spatie\Permission\Models\Role;
use Spatie\Permission\Traits\HasRoles;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Model;
class User extends Authenticatable
{
    use Notifiable;
    use SoftDeletes, HasApiTokens;
    use HasRoles;
protected $fillable = [
        'user_id', 'profile_image', 'name', 'email', 'address','phone','location','role_id','auth_type', 'password','status'
    ];
protected $hidden = [
        'password', 'remember_token',
    ];
public function role()
    {
        return $this->belongsToMany(Role::class, 'role_id');
    }
}

UserController

UserController.php

use Spatie\Permission\Models\Role;
use App\Http\Requests\UserCreateRequest;
public function saveUser(UserCreateRequest $request)
{
$user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'role_id' => $request->role_id,
            'status' =>0,
        ]);
        $role = Role::find($request->role_id);
        $user->assignRole([$role->name]);
}

When i try to create a new user it shows an error
BadMethodCallException
Call to undefined method Illuminate\Database\Eloquent\Relations\BelongsTo::sync()

Here only need role option without any permissions

enter image description here

CodePudding user response:

enter image description here

Here is your solution, as given in the documentation.

  • Related