欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

[Illuminate\Database\Eloquent\ModelNotFoundException] No query results for model [App\Role]. How to handle "No query results for model"

如何处理“没有模型的查询结果”

 

ORTIX 发表于2年前

正如标题所示,我们如何处理这样的错误?

在我的具体情况下,uri中的slug不存在,我正在搜索数据库中的这个lug子。如果不存在,则会抛出此错误。我想要一个404错误出现。怎么处理这个?

    public function getBySlug($slug)
    {
        // TODO: handle fail
        $show = Show::where('slug', '=', $slug)->firstOrFail();
        return $show;
    }
bashy
 bashy

 

2年前(1,047,440 XP)

我不知道,有几种方法,也许这个?

if ( ! $show)
{
    App::abort(404);
}
 
美国人
美国人

 

2年前(127,195 XP)

该方法在没有找到与查询匹配的记录时firstOrFail()抛出Illuminate\Database\Eloquent\ModelNotFoundException你可以在你的错误处理程序的一个捕获这个异常,在解释返回一个404响应文件

//file app/start/global.php
App::error(function(Illuminate\Database\Eloquent\ModelNotFoundException $e){
    return Response::make('Not found',404);
    //or
    //return Response::view('404-view',null,404);
});
 
pmall
 pmall

 

2年前(574,745 XP)

我什么都不做 如果这样的话,恶意用户会试图访问非优质的东西。哎哟,他们错了就可以了。

 
luanrodriguesp
 luanrodriguesp

 

2年前(5,825 XP)

@usman 在L5哪里可以把代码放在哪里?

谢谢。

 
JarekTkaczyk
 JarekTkaczyk

 


来自 https://laracasts.com/discuss/channels/general-discussion/how-to-handle-no-query-results-for-model?p...

How to handle "No query results for model"



PUBLISHED 2 YEARS AGO BY ORTIX

As the title says, how do we go about handling such an error?

In my specific case the slug in the uri doesn't exist and I'm searching the database for that slug. If it doesn't exist, this error is thrown. I want a 404 error to appear. How would one go about handling this?

    public function getBySlug($slug)
    {
        // TODO: handle fail
        $show = Show::where('slug', '=', $slug)->firstOrFail();
        return $show;
    }
bashy
 bashy
2 years ago(1,047,440 XP)

I don't know, there's a few ways, maybe this?

if ( ! $show)
{
    App::abort(404);
}
 
美国人
usman
2 years ago(127,195 XP)

The method firstOrFail() throws an Illuminate\Database\Eloquent\ModelNotFoundException when it does not find a record matching the query. You can catch this exception in one of your error handlers to return a 404 response as explained in documentation.

//file app/start/global.php
App::error(function(Illuminate\Database\Eloquent\ModelNotFoundException $e){
    return Response::make('Not found',404);
    //or
    //return Response::view('404-view',null,404);
});
 
pmall
 pmall
2 years ago(574,745 XP)

I would do nothing. If something like this appends its that a malicious user try to access non exising stuffs. Whooops somethig went wrong is ok for them.

 
luanrodriguesp

@usman in L5 where shuould i put the code?

thank you.

 

来自 https://laracasts.com/discuss/channels/general-discussion/how-to-handle-no-query-results-for-model?p...


普通分类: