Skip to main content
Tutorial Free

Laravel Route Model Binding Returns NULL Object: What To Do

February 05, 2023
1 min read

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.

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Recent Courses

[NEW] Building a Typical Laravel SaaS

10 lessons
1 h 27 min

Filament 4 From Scratch

28 lessons
2 h 25 min

Laravel HTTP Client and 3rd-Party APIs

7 lessons
50 min

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.