patternphplaravelTip
Route Model Binding: Implicit vs Explicit and Customisation
Viewed 0 times
route model bindingimplicit bindingexplicit bindinggetRouteKeyNameslug404findOrFail
Error Messages
Problem
Controllers manually fetch models with findOrFail() on every action, duplicating boilerplate and missing consistent 404 handling.
Solution
Use implicit route model binding by type-hinting the model in the controller method and matching the route parameter name to the model variable name. Override the default key with ->bindingField() on the route or implement getRouteKeyName() on the model to use a slug. Use explicit binding in RouteServiceProvider for complex resolution logic.
Why
Laravel's implicit binding automatically resolves and injects the model, throwing a 404 ModelNotFoundException if not found. This eliminates boilerplate and centralises not-found handling.
Gotchas
- The route parameter name must match the controller argument name exactly
- Soft-deleted models are excluded by default; use ->withTrashed() on the route to include them
- Scoped bindings (child routes scoped to parent) require ->scopeBindings() in Laravel 9+
- Custom key binding via getRouteKeyName() affects all routes—use per-route binding for more control
Code Snippets
Implicit binding and custom key
// routes/web.php
Route::get('/posts/{post:slug}', [PostController::class, 'show']);
// Controller - $post is resolved automatically
public function show(Post $post): View
{
return view('posts.show', compact('post'));
}Revisions (0)
No revisions yet.