Route Model Binding
When injecting a model ID to a route or controller action, you will often query the database to retrieve the model that corresponds to that ID. Laravel route model binding provides a convenient way to automatically inject the model instances directly into your routes. For example, instead of injecting a user’s ID, you can inject the entire User
model instance that matches the given ID.
Implicit Binding
Laravel automatically resolves Eloquent models defined in routes or controller actions whose type-hinted variable names match a route segment name. For example:
use App\Models\User;
Route::get('/users/{user}', function (User $user) {
return $user->email;
});
Since the $user
variable is type-hinted as the App\Models\User
Eloquent model and the variable name matches the {user}
URI segment, Laravel will automatically inject the model instance that has an ID matching the corresponding value from the request URI. If a matching model instance is not found in the database, a 404 HTTP response will automatically be generated.
Of course, implicit binding is also possible when using controller methods. Again, note the {user}
URI segment matches the $user
variable in the controller which contains an App\Models\User
type-hint:
use App\Http\Controllers\UserController;
use App\Models\User;
// Route definition...
Route::get('/users/{user}', [UserController::class, 'show']);
// Controller method definition...
public function show(User $user)
{
return view('user.profile', ['user' => $user]);
}