Beyond 404: Smart Model Binding Responses in Laravel

Explanation:
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.
Code:
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.'); });
Comments :