Laravel Route Model Binding Returns NULL Object: What To Do

When using Route Model Binding in Laravel, it's important to have the same name of the parameter in the routes file and in the method variable name.

Here's an example that would NOT work.

routes/web.php:

Route::get('users/{user}', [UserController::class, 'show']);

UserController.php:

public function show(User $userData) {
// ...
}

As a result, route model binding won't work, and $userData will be NULL.

That's because the {user} is called differently than $userData.

The variable should be named exactly the same as the parameter.

UserController.php:

public function show(User $user) { // NOT $userData
// ...
}

The same applies to the Resource Controllers.

routes/web.php:

Route::resource('users', UserController::class);

In this case, methods like show(User $user), edit(User $user), and others where you want to use Route Model Binding, should have the parameter named $user and not something different like $userData or $member.

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 59 courses (1057 lessons, total 42 h 44 min)
  • 78 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials