Laravel 5.4 | NotFoundHttpException 的自定义页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42684854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:30:55  来源:igfitidea点击:

Laravel 5.4 | Custom Page for NotFoundHttpException

laravellaravel-5.4

提问by whitecollar

I am trying to redirect the user to a custom 404 page in case of NotFoundHttpException in Laravel 5.4

我正在尝试将用户重定向到自定义 404 页面,以防 Laravel 5.4 中出现 NotFoundHttpException

To do so, I added following piece of code in App\Exceptions\Handler.php file:

为此,我在 App\Exceptions\Handler.php 文件中添加了以下代码:

public function render($request, Exception $exception)
{
    if ($exception instanceof NotFoundHttpException) {
        if ($request->expectsJson()) {
            return response()->json(['error' => 'Not Found'], 404);
        }
        return response()->view('404', [], 404);
    }
    return parent::render($request, $exception);
}

For some reason this doesn't work. Can someone please point if I am doing something wrong here?

出于某种原因,这不起作用。如果我在这里做错了什么,有人可以指出吗?

Thanks!

谢谢!

回答by Josh Bolton

Laravel will render your error pages before falling back on the default view.

Laravel 将在返回默认视图之前呈现您的错误页面。

If your view is created in: resources/views/errors/404.blade.php. This page will be rendered before the fallback error page.

如果您的视图是在以下位置创建的:resources/views/errors/404.blade.php. 此页面将在后备错误页面之前呈现。

The views in the above directory should have the names of the HTTP status code which you are trying to render.

上述目录中的视图应具有您尝试呈现的 HTTP 状态代码的名称。

More information can be found in the laravel docs:

更多信息可以在 laravel 文档中找到:

https://laravel.com/docs/5.4/errors#custom-http-error-pages

https://laravel.com/docs/5.4/errors#custom-http-error-pages

回答by EddyTheDove

Just create your view here

只需在此处创建您的视图

resources/views/errors/404.blade.php

Laravel will serve it automatically for you

Laravel 会自动为你服务

回答by francis ngangue

You do not need to modify the render function. Keep it like the original:

您不需要修改渲染功能。保持原样:

public function render($request, Exception $exception)
{
    return parent::render($request, $exception);
}

All you have to do is just make the view:

您所要做的就是创建视图:

resources/views/errors/404.blade.php

资源/视图/错误/404.blade.php

Then add some contents to the file, for example:

然后在文件中添加一些内容,例如:

@extends('layouts.app')

@section('content')
404
@endsection

Laravel takes care of the rest...

Laravel 负责其余的工作......