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

Hello Artisan, today I'll show you How To Handle "No Query Results For Model" Error in our Laravel application. Here is a simple example that demonstrates how to handle "No query results for model" errors in Laravel 10. If you have any questions regarding this specific error in Laravel 10, I can provide you with a straightforward solution.

By following this example, you will understand how to effectively manage and resolve such errors in your Laravel 10 application without altering the core functionality described in the initial explanation.

Table of Contents

  1. Install Laravel
  2. Add Controller
  3. Handle Exception

Install Laravel

Creating the Laravel app is not necessary for this step, but if you haven't done it yet, you can proceed by executing the following command

composer create-project laravel/laravel error-handler

Add Controller

php artisan make:controller ModelController
app/Http/Controllers/ModelController.php
<?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\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * The list of the inputs that are never flashed to the session on validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     */
    public function report(Exception|Throwable $exception)
    {
        parent::report($exception);
    }

    public function render($request, Exception|Throwable $e)
    {
        if ($e instanceof ModelNotFoundException) {
            return response()->json(['error' => 'Data not found.']);
        }

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

That's it for today. I hope it'll be helpful in upcoming project. You can also download this source code from GitHub. Thanks for reading. ๐Ÿ™‚