>通過優雅地處理模型綁定故障來增強您的Laravel應用程序。 而不是通用404錯誤,而是利用Laravel的missing
方法來創建改善用戶體驗的自定義響應。在處理URL更改,更名的產品或為缺失資源提供有用的建議時,這尤其有價值。
此技術允許複雜的錯誤處理超出簡單的404頁。
這是使用>方法實現智能重定向的方法:missing
>
Route::get('/articles/{article:slug}', [ArticleController::class, 'show']) ->missing(function (Request $request) { return redirect()->route('articles.index') ->with('message', 'Article not found'); });
// Route for archived articles Route::get('/articles/{article:slug}', [ArticleController::class, 'show']) ->missing(function (Request $request) { // Check for archived article $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.'); });
例如:
>通過使用
<code>// Accessing /articles/old-article-slug // Redirects to /articles/archived/old-article-slug // With flash message: "This article has been moved to our archive."</code>
以上是超過404:Laravel中的智能模型構圖響應的詳細內容。更多資訊請關注PHP中文網其他相關文章!