使用Laravel 5在404网址上安装控制器

时间:2017-07-03 14:02:34

标签: laravel laravel-5

当用户点击不存在的url或我以编程方式强制App :: abort(404)时,我需要触发自定义控制器。

我该怎么做?

我的404视图需要一些数据,而简单的刀片视图(或ViewComposer)是不够的。

由于

PS catch-all urls不起作用,因为它们没有以编程方式启动404。

2 个答案:

答案 0 :(得分:0)

修改render课程的App\Exceptions\Handler功能,并在此处添加404的内容:

if ($this->isHttpException($exception) && $this->getStatusCode() == 404) {
    // Do what you want...
    // You can even use the $request variable
}

完整示例:

public function render($request, Exception $exception)
{
    if ($this->isHttpException($exception) && $this->getStatusCode() == 404) {
        echo 'hello from 404 renderer';
        dd($request); // Or you can a view.
    }
    return parent::render($request, $exception);
}

答案 1 :(得分:0)

如果异常是redirect() Controller方法,请尝试将response()返回到自定义Handler而不是render() 404。您可以从$request检索所请求的页面吗?

以下是样本:

public function render($request, Exception $exception)
{
    if ($this->isHttpException($exception) && $this->getStatusCode() == 404) {
        return redirect(route('route.to.custom.controller'))->with('request', $request);
    }

    return parent::render($request, $exception);
}
希望这会有所帮助,干杯!