当用户点击不存在的url或我以编程方式强制App :: abort(404)时,我需要触发自定义控制器。
我该怎么做?
我的404视图需要一些数据,而简单的刀片视图(或ViewComposer)是不够的。
由于
PS catch-all urls不起作用,因为它们没有以编程方式启动404。
答案 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);
}
希望这会有所帮助,干杯!