Laravel 5.2如何将所有404错误重定向到主页

时间:2016-03-01 08:16:31

标签: laravel redirect http-status-code-404 http-status-code-301 laravel-5.2

如何将所有404错误重定向到主页?我有自定义错误页面,但谷歌分析错误太多了。

2 个答案:

答案 0 :(得分:16)

为此,您需要在render文件中为app/Exceptions/Handler.php方法添加几行代码。

public function render($request, Exception $e)
{   
    if($this->isHttpException($e))
    {
        switch (intval($e->getStatusCode())) {
            // not found
            case 404:
                return redirect()->route('home');
                break;
            // internal error
            case 500:
                return \Response::view('custom.500',array(),500);
                break;

            default:
                return $this->renderHttpException($e);
                break;
        }
    }
    else
    {
        return parent::render($request, $e);
    }
}

答案 1 :(得分:0)

对于使用php 7.2 + Laravel 5.8的我来说,它像老板一样工作。 我更改了渲染方法(app / Exceptions / Handler.php)。 因此,我们必须检查该异常是否为HTTP异常,因为我们正在调用getStatusCode()方法,该方法仅在HTTP异常中可用。 如果状态码为404,我们可能会返回一个视图(例如:errors.404)或重定向到某个地方或路线(家)。

  

app / Exceptions / Handler.php

public function render($request, Exception $exception)
    {

        if($this->isHttpException($exception)) {
            switch ($exception->getStatusCode()) {
                // not found
                case 404:
                    return redirect()->route('home');
                    break;

                // internal error
                case 500:
                    return \Response::view('errors.500', [], 500);
                    break;

                default:
                    return $this->renderHttpException($exception);
                    break;
            }
        } else {
            return parent::render($request, $exception);
        }

    }

要测试:添加中止(500);控制器流程中的某个位置以查看页面/路由。我用了500,但是您可以使用以下错误代码之一:Abort(404)...

abort(500);

(可选)我们可以提供回复:

abort(500, 'What you want to message');
相关问题