Laravel framework's Route::fallback
method provides an elegant way to handle requests that do not match any defined route. Rather than displaying a common 404 page, create a more meaningful experience for users who visit non-existent pages.
This feature is especially valuable for maintaining user engagement, especially when pages are moved or renamed, or when older URLs are processed in older systems. It can also be used to collect data about missing pages, thereby informing your website structure and content strategy.
The following is a simple example, using Route::fallback
to return a custom 404 error page:
Route::fallback(function () { return view('errors.404') ->with('message', '页面未找到'); });
You can also use the Request
object to get more context information:
use Illuminate\Http\Request; Route::fallback(function (Request $request) { // 获取当前路径 $path = $request->path(); // 检查是否是API请求 if ($request->expectsJson()) { return response()->json(['error' => '未找到'], 404); } return view('errors.404', compact('path')); });
With a custom fallback
Routing processor, you can turn potential frustrating 404 errors into opportunities to increase user engagement and collect valuable analytics data.
The above is the detailed content of Handling Unmatched Routes in Laravel. For more information, please follow other related articles on the PHP Chinese website!