在ArticleContronller.php中出现数据获取不存在时
public function show($id) {
$article=Arrticle::find($id)
if(is_null($article)){
abort(404)
}
return view(articles.show,compact('article'));
}
注:关于abort()与exit()
exit和abort都是用来终止程序的函数,他们的不同如下:
exit会做一些释放工作:释放所有的静态的全局的对象,缓存,关掉所有的I/O通道,然后终止程序。如果有函数通过atexit来注册,还会调用注册的函数。不过,如果atexit函数扔出异常的话,就会直接调用terminate。
abort:立刻terminate程序,没有任何清理工作。
参考:http://bbs.csdn.net/topics/390130642
注:
Q:Laravel app:abort(404) not showing 404 page
I have a route of /path/{id}, and I want my controller to detect when the id is invalid and product a 404 error page. I tried using App::abort(404);, but this doesn’t produce a 404 error - just a generic exception. How do I make it generate a 404 page?
A:You have to use the Response::make or Response::view functions to generate a specific page. You can pass the error code as an argument to that. Like this:
Response::make("Page not found", 404);
Or to use a specific view, use:
return Response::view('404', array(), 404);
To display the view app/views/404.php with the http response code 404. Remember to replace the slashes with dots for the view name, so if your file is at app/views/errors/404.php, you will need to use the view name ‘errors.404’ for laravel to find it.
参考:http://*.com/questions/22011202/laravel-appabort404-not-showing-404-page
注:
当命名空间不一致时,注意使用方式
\App::abort(404);
app()->abort(404);
参考https://laravel-china.org/topics/1385/laravel-5-how-to-use-app-correctly-abort-404
使用findorFail()
public function show($id) {
$article=Arrticle::findorFail($id)
if(is_null($article)){
abort(404)
}
return view(articles.show,compact('article'));
}