Laravel Route Binding Null/Empty Object
Laravel’s routing and binding is nice
But when I got it wrong I didn’t get the kind of error I expected
Laravel automatically resolves Eloquent models defined in routes or controller actions whose type-hinted variable names match a route segment name.
use App\Models\User;
Route::get('/users/{user}', function (User $user) {
return $user->email;
});
This works for controller methods too.
Couple of things to note here
First - the type hinted model is matched by name - and it’s case sensitve
So this
use App\Models\User;
Route::get('/users/{User}', function (User $user) {
return $user->email;
});
Won’t work because $User
and $user
are not the same thing in PHP.
Secondly the way it doesn’t work surprised me.
There were no warnings about a type mismatch, and not 404 returned as you’d expect for an invalid ID.
Instead what I got passed to my method was a null object of the right type but with no properties.
So my code failed when I looked for expected properties.
When I ran dd()
I saw the right type of object - bit without the data I expected.