Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ortix's avatar

How to handle "No query results for model"

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;
    }
0 likes
6 replies
bashy's avatar

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

if ( ! $show)
{
    App::abort(404);
}
usman's avatar

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);
});
5 likes
pmall's avatar

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.

nurulfitriany's avatar

I agree with @usman , but if there is pop up error telling you that ---No query results for model--- this is means app[name class] has problem within it. You have to figure it out your database model within it

Please or to participate in this conversation.