>通過優雅地處理模型綁定故障來增強您的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個錯誤轉換為平滑的重定向和信息豐富的消息,從而創建一個更具用戶友好和強大的應用程序。
以上是超過404:Laravel中的智能模型構圖響應的詳細內容。更多資訊請關注PHP中文網其他相關文章!