Laravel —— 自定义 404 处理方式
Laravel 有自己的 404 处理方式及对应的页面
大多项目中都需要定义自己的 404 页面
有些时候 404 页面中有动态数据
本篇文章的使用 Laravel 9
一、自定义 404 页面
方案一、在 resources/views/errors/ 创建 404.blade.php 文件,
方案二、用命令发布模板,php artisan vendor:publish --tag=laravel-errors
再次访问不存在的路由时,就会显示自己定义的 404 内容。
二、404 添加动态数据
框架的异常处理都在 app/Exceptions/Handler.php 中。
继承了 vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php 文件。
方案一、重写异常处理方法
找到渲染异常的方法,并重写
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
// 状态为 404 时。把 data 渲染到 404 页面
// 其他状态,按照自带的逻辑处理
public function render($request, Throwable $e)
{
if ($e instanceof NotFoundHttpException) {
if (view()->exists($view = 'errors.404')) {
return response()->view($view, [
'data' => 'test',
], $e->getStatusCode(), $e->getHeaders());
}
}
return parent::render($request, $e);
}
方案二、注册自定义的渲染闭包
在 register 方法中,添加自定义 404 渲染
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
public function register()
{
$this->reportable(function (Throwable $e) {
//
});
$this->renderable(function (NotFoundHttpException $e, $request) {
if (view()->exists($view = 'errors.404')) {
return response()->view($view, [
'data' => 'test',
], $e->getStatusCode(), $e->getHeaders());
}
});
}
再次访问不存在的路由,动态数据可以在 404 页面显示出来。