How To Handle "No Query Results For Model" Error - Laravel 8


Share:
Published By: Admin, Published On: Oct 27, 2021, Category: Laravel 8 Laravel


Hello Friends,

Yesterday, I was just working on my restful API with User model and I found following error on show method: "No query results for the model [App\\User] 1", first I search on google about No query results for a model issue and fix that. but I want to understand why this error comes. i found why No query results for the model is an error on show, edit and update method when you used a model as a parameter. So basically when you pass id in URL then laravel model will check id is found or not on given model. So it returns ModelNotFoundException exception. we can return as a response.

We can simple handle exception and return a better response. So just we will handle ModelNotFoundException on our Handler.php file. So you need to just add following code to your Handler.php.

I am going to give you full error so let's understand what i write and what is the issue i fetched and how to resolved that.

My Controller Method :
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ModelController extends Controller
{
	/**
    * Display the specified resource.
    *
    * @param  \App\Models\Model  $Model
    * @return \Illuminate\Http\Response
    */
    public function show(User $user)
    {
        return response()->json($user->toArray());
    }
}
My Error :
No query results for model [App\\User] 1
Handle Exception : app/Exceptions/Handler.php
<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Database\Eloquent\ModelNotFoundException;

class Handler extends ExceptionHandler
{
    /**
    * A list of the exception types that are not reported.
    *
    * @var array
    */
    protected $dontReport = [
        //
    ];

    /**
    * A list of the inputs that are never flashed for validation exceptions.
    *
    * @var array
    */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
    * Report or log an exception.
    *
    * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
    *
    * @param  \Exception  $exception
    * @return void
    */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
    * Render an exception into an HTTP response.
    *
    * @param  \Illuminate\Http\Request  $request
    * @param  \Exception  $exception
    * @return \Illuminate\Http\Response
    */
    public function render($request, Exception $exception)
    {
        if ($e instanceof ModelNotFoundException) {
            return response()->json(['error' => 'Data not found.']);
        }

        return parent::render($request, $exception);
    }
}

I hope it can help you...

Share: