Home > Mobile >  1048 Column 'user_id' cannot be null when trying to assign role to existing user Laravel
1048 Column 'user_id' cannot be null when trying to assign role to existing user Laravel

Time:05-05

I want to assign role to existing user but I'm getting this error.

My User Controller:

 public function show(User $user) {
    return view('admin.users.profile', [
        'user' => $user,
        'roles' => Role::all(), 
    ]);

  public function attach(User $user) {
  $user->roles()->attach(request('role'));
  return back();
  }

My form:

<form method="post" action="{{route('user.role.attach', $user)}}">
                    @csrf
                    @method('PUT')
                    <input type="hidden" name="role" value="{{$role->id}}">
                    <button >Attach</button>
                </form>

I am getting this error in browser:

insert into `role_user` (`role_id`, `user_id`) values (2, ?)

So I suppose that I'm not returning user_id, only role_id by clicking on button for attaching..

CodePudding user response:

You didn't bind user in your route. It need to be something like:

Route::put('/users/{user}/attach', [App\Http\Controllers\UserController::class, 
'attach'])->name('user.role.attach');

You can of course modify a little bit your route but most important thing here is that you expect User in controller but you didn't bind in route ;)

  • Related