关于数据获取时不存在时的404报错处理方案

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://stackoverflow.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'));
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值