Route Model Binding
Route Model Binding is one of Laravel's most elegant features — it automatically resolves Eloquent models from route parameters. Instead of manually fetching Post::findOrFail($id) in every controller method, type-hint the model and Laravel does the query automatically, injecting the instance or returning a 404 if not found. This eliminates boilerplate, reduces bugs, and makes controllers dramatically cleaner.
Implicit Binding
// Type-hint the model — Laravel resolves automatically
Route::get('/posts/{post}', function (Post $post) {
return view('posts.show', compact('post'));
});
// Laravel executes: Post::findOrFail($routeValue)
// Returns 404 if not found — no manual handling needed
// In controllers — same magic applies
public function show(Post $post): View
{
return view('posts.show', compact('post'));
}
// Use slug instead of id — override getRouteKeyName() in model
public function getRouteKeyName(): string
{
return 'slug'; // Route {post} now resolves by slug column
}
// Scoped binding — child must belong to parent
// GET /users/{user}/posts/{post:slug}
Route::get('/users/{user}/posts/{post:slug}',
function (User $user, Post $post) {
// $post is automatically scoped: WHERE user_id = $user->id
return view('users.posts.show', compact('user', 'post'));
}
);
// Returns 404 if post exists but doesn't belong to this userExplicit Binding
// Register in RouteServiceProvider (or bootstrap/app.php in Laravel 11)
Route::bind('post', function (string $value) {
return Post::where('slug', $value)
->where('published', true)
->firstOrFail();
// Only resolves published posts — drafts return 404
});
// Custom resolution for complex scenarios
Route::bind('invoice', function (string $value) {
return Invoice::where('reference_number', $value)
->where('user_id', auth()->id())
->firstOrFail();
// Users can only access their own invoices
});
// Model method alternative (cleaner)
// In Post model:
public function resolveRouteBinding($value, $field = null)
{
return $this->where('slug', $value)
->where('published', true)
->firstOrFail();
}Tip
Tip
Practice Route Model Binding in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Local scopes for reusable filters (scopePublished, scopeRecent). Global scopes for always-on filters (multi-tenancy).
Practice Task
Note
Practice Task — (1) Write a working example of Route Model Binding from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Route Model Binding is skipping edge case testing — empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready laravel code.