我有一个PageController,它正在显示页面的内容,但首先我需要检查输入的URL是否存在,只有在这种情况下,我才会显示该页面。
不幸的是,如果搜索到的页面不存在,则会抛出异常:
NotFoundHttpException in Handler.php line 103:
No query results for model [App\Models\PageTranslation].
这是我的代码,如果没有发现任何错误,我会尝试将其重定向到错误404,但仍然会给我NotFoundHttpException。
public function show($page) {
$lang = Lang::getLocale();
$page = $this->page_translation->where('slug', '=', $page)->where('lang', '=', $lang)->firstOrFail();
if(!$page) {
App::abort(404);
}
return view('front.page.show', compact('page'));
}
在这种情况下,我如何将用户重定向到“错误404”页面?
使用first()
代替firstOrFail()
。firstOrFail()
如果没有匹配的数据,则立即失败(抛出404),并且不会遍历其余代码,而first()
返回null
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句