Laravel Tutorials

Beyond 404: Smart Model Binding Responses in Laravel

Published
Beyond 404: Smart Model Binding Responses in Laravel image

Laravel's missing method offers a sophisticated way to customize responses when model binding fails. Instead of showing generic 404 pages, you can create meaningful redirects or responses that enhance user experience.

This approach is particularly useful for handling URL changes, product renames, or providing smart suggestions when users encounter missing resources.

Route::get('/articles/{article:slug}', [ArticleController::class, 'show'])
    ->missing(function (Request $request) {
        return redirect()->route('articles.index')
            ->with('message', 'Article not found');
    });

Here's a practical example with smart redirects:

// Archive articles route
Route::get('/articles/{article:slug}', [ArticleController::class, 'show'])
    ->missing(function (Request $request) {
        // Check if article was moved to archive
        $archived = ArchivedArticle::where('original_slug', $request->route('article'))
            ->first();

        if ($archived) {
            return redirect()
                ->route('articles.archived', $archived->slug)
                ->with('info', 'This article has been moved to our archive.');
        }

        return redirect()
                ->route('articles.index')
                ->with('info', 'Article not found. Browse our latest posts.');
    });

When a user attempts to access a moved article, they'll be smoothly redirected:

// When accessing /articles/old-article-slug
// User gets redirected to /articles/archived/old-article-slug
// With flash message: "This article has been moved to our archive."

The missing method transforms frustrating 404 experiences into helpful redirects and informative messages.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
Laravel Read Replicas: Check if a Replica Has Caught Up image

Laravel Read Replicas: Check if a Replica Has Caught Up

Read article
UUID Request Input and Migration Failure Events in Laravel 13.42 image

UUID Request Input and Migration Failure Events in Laravel 13.42

Read article
Replay Missed Laravel Scheduled Tasks With Schedule Catchup image

Replay Missed Laravel Scheduled Tasks With Schedule Catchup

Read article
Search Polymorphic Relations and Filament Tables With Laravel Searchable image

Search Polymorphic Relations and Filament Tables With Laravel Searchable

Read article
Laravel Rest Api 3.0: Typed Fields, Metrics, and OpenAPI Docs image

Laravel Rest Api 3.0: Typed Fields, Metrics, and OpenAPI Docs

Read article
Real-Time Inertia Props With Laravel Reverb image

Real-Time Inertia Props With Laravel Reverb

Read article