How to fix 1048 Column ‘user_id’ cannot be null in Laravel

Working with robust applications built in Laravel framework starts throwing errors which happens because of missing minor things. One of the common error is 1048 Column ‘user_id’ cannot be null when trying to assign role to existing user. Lets explain this with a code example.

Code Example: A column cannot be null

Lets have a scenario, where we want to assign role to a user. We have this user exists in our database. For this, we will need three things

  1. Route
  2. Form
  3. Controller

Route:

In below route, we are defining a path ‘/users/attach’ and pointing it to a controller method attach. We are naming this route as user.role.attach

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

Form:

Now, in blade.php file, we will create a form like below, where action attribute will call on the route name user.role.attach, which is pointing to method attach() in the controller. In the form, we are passing a role which carries role id.

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

Controller:

In below controller we have following methods, one of them is attach(User $user), now the values inside attach() method which is User $user is expecting a value from the route. our above defined route is ‘/users/attach’

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

If we run our application it will start throwing following error, because there is not value in route path ‘/users/attach’

1048 Column 'user_id' cannot be null when trying to assign role to existing user

This error happens because in Controller method attach() we are expecting user details (user_id). If method do not find user_id, it will throw error.

Solution to Column cannot be null:

We can adjust our route to pass user id {}, so we can we can receive it in our controller and assign a role to specified user.

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 😉

Recommend Post: laravel.log could not be opened

Recommend Post: how to force https in laravel