如何实现404页面?方法其实有很多种,接下来本篇文章就给大家介绍如何用laravel 5.5+框架更好的来实现404响应,话不多说,让我们来看一看具体的内容。
Laravel 5.5.10 封装了两个有用的路由器方法,可以帮助我们为用户提供更好的 404 页面。现在,当抛出 404 异常时,Laravel 会显示一个漂亮的 404.blade.php 视图文件,你可以自定义显示给用户 UI,但在该视图中,你无权访问 session,cookie,身份验证(auth)等...
在 laravel 5.5.10 中,我们有一个新的 Route::fallback() 方法,用于定义当没有其他路由与请求匹配时 Laravel 回退的路由。
Route::fallback(function () {
return 'Sorry' . auth()->user()->name . '! This page does not exist.';
});所以,现在我们可以使用具有正常页面和页脚的应用布局,来替代简单的 404 视图,同时还能给用户显示一条友好的提示信息。
Route::fallback(function() {
return response()->view('notFound', [], 404);
});@extends('layout.app')
@section('content')
<h3>Sorry! this page doesn't exist.</h3>
@stop当 Laravel 渲染这个回退(fallback)路由时,会运行所有的中间件,因此当你在 web.php 路由文件中定义了回退路由时,所有处在 web 中间件组的中间件都会被执行,这样我们就可以获取 session 数据了。
现在当你点击 /non-existing-page 时,你会看到在回退路由中定义的视图,甚至当你点击 /api/non-existing-endpoint 时,如果你也不想提供这个接口,你可以到 api 回退路由中定义 JSON 响应,让我们到 api.php 路由文件中定义另外一个回退路由:
Route::fallback(function() {
return response()->json(['message' => 'Not Found!]);
});由于 api 中间件组带有 /api 前缀,所有带有 /api 前缀的未定义的路由,都会进入到 api.php 路由文件中的回退路由,而不是 web.php 路由文件中所定义的那个。
当使用 abort(404) 时会抛出一个 NotFoundHttpException,此时处理器会为我们渲染出 404.blade.php 视图文件,同样的 ModelNotFoundException 异常也会做同样的处理,那么我们应该如何如何处理才能在更好的渲染出回退路由的视图,而不是一个普通的视图呢?
class Handler extends ExceptionHandler
{
public function render($request, Exception $exception)
{
if ($exception instanceof NotFoundHttpException) {
return Route::responseWithRoute('fallback');
}
if ($exception instanceof ModelNotFoundException) {
return Route::responseWithRoute('fallback');
}
return parent::render($request, $exception);
}
}Route::respondWithRoute('fallback') 回去跑名为 fallback 的路由,我们可以像下面这样为回退路由命名:
Route::fallback(function() {
return response()->view('notFound', [], 404);
})->name('fallback');甚至,你还可以为特定的资源指定回退路由:
if ($exception instanceof ModelNotFoundException) {
return $exception->getModel() == Server::class
? Route::respondWithRoute('serverFallback')
: Route::respondWithRoute('fallback');
}现在我们需要在路由文件中定义这个回退路由:
Route::fallback(function(){
return 'We could not find this server, there are other '. auth()->user()->servers()->count() . ' under your account ......';
})->name('serverFallback');相关推荐:
mac mamp ngiux laravel框架 报404错误
以上就是如何用Laravel 5.5+框架更好的来实现404响应的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号