php 89 lines · 3 tabs

Laravel route model binding

Carlos Mendez Jan 2026
3 tabs
<?php

use App\Models\Post;
use App\Models\Comment;
use Illuminate\Support\Facades\Route;

// Implicit binding - auto-resolves Post by ID
Route::get('/posts/{post}', function (Post $post) {
    return view('posts.show', compact('post'));
});

// Bind by slug instead of ID
Route::get('/posts/{post:slug}', function (Post $post) {
    return view('posts.show', compact('post'));
});

// Scoped binding - ensures comment belongs to post
Route::get('/posts/{post}/comments/{comment}', function (Post $post, Comment $comment) {
    return view('comments.show', compact('post', 'comment'));
})->scopeBindings();

// Include soft-deleted models
Route::get('/posts/{post}', function (Post $post) {
    return view('posts.show', compact('post'));
})->withTrashed();

// Custom missing behavior
Route::get('/posts/{post}', function (Post $post) {
    return view('posts.show', compact('post'));
})->missing(function () {
    return response()->view('errors.404', [], 404);
});
3 files · php Explain with highlit

Route model binding automatically resolves Eloquent models from route parameters, eliminating manual lookups. Implicit binding matches parameter names to model IDs—/users/{user} injects the User model. Custom route keys use getRouteKeyName() to bind by slug instead of ID. Explicit binding in RouteServiceProvider provides full control over resolution logic. Soft-deleted models are excluded unless using withTrashed(). Scoped bindings enforce parent-child relationships—/posts/{post}/comments/{comment} ensures the comment belongs to the post. Missing models return 404 automatically. This feature reduces boilerplate and improves security by centralizing authorization checks.


Related snips

Share this code

Here's the card — post it anywhere.

Laravel route model binding — share card
Link copied