How to return custom view for http error response

2019-06-28 07:19发布

How Can I define custom View files for each of http error responses and then ask laravel to send that view file automatically to user when I'm returning an http error response in my application?

2条回答
forever°为你锁心
2楼-- · 2019-06-28 07:44

Basically you can define a page for every HTTP error code and put it in resources/views/errors/

So, if you want to create a view for a 404 HTTP response you should create the view:

resources/views/errors/404.blade.php

and Laravel will redirect automatically your users to the specific view

Additionally, you can customize the App\Exceptions\Handler class that is responsable for rendering errors from exceptions: the render method is called everytime an Exception rises, so you can intercept the HttpException generated by the HTTP error and redirect wherever you want:

public function render($request, Exception $e)
{
    //if $e is an HttpException
    if ($e instanceof HttpException ) {

        //get the status code 
        $status = $e->getStatusCode() ;

        //if status code is 501 redirect to custom view
        if( $status == 501 )
            return response()->view('my.custom.view', [], 501);
    }

    return parent::render($request, $e);
}
查看更多
手持菜刀,她持情操
3楼-- · 2019-06-28 07:54

First in .env file change APP_DEBUG=true to APP_DEBUG=false
Second create your custom file and rename to 404.balde.php and copy to

resources/views/errors/404.blade.php
查看更多
登录 后发表回答