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...