Tutorial Details

How To Handle No Query Results For Model in Laravel 10
25 Nov

How To Handle No Query Results For Model in Laravel 10

Hi Guys,

This article will provide an example of Laravel 10 no query results for the model. you can see no query results for model exception Laravel. if you want to see an example of no query results for model Laravel 10 then you are in the right place. If you have a question about Laravel handling no query results for the model then I will give a simple example with a solution. Here, Create a basic example of Laravel catches no query results for the model.

In Laravel, the "No query results for model" exception is a common exception that occurs when you try to fetch a record from the database using Eloquent, Laravel's built-in ORM (Object-Relational Mapping), but no matching record is found. This exception is thrown by Laravel to handle such cases.

I will give you a simple solution to fix this issue using ModelNotFoundException. so, let's see the simple solution.

Controller Code:

you will have the following user controller code:

app/Http/Controllers/UserController.php

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;

class UserController extends Controller

{

    /**
     * Write code on Method
     *
     * @return response()
     */

    public function show(User $user)

    {

        return response()->json($user->toArray());

    }

}

Now, if you pass the correct existing user ID on the URL then it works fine as like below:

http://localhost:8000/users/1

it returns a proper JSON response:

{"id":1,"name":"Antonia Ortiz","email":"ulegros@example.com","type":0,"email_verified_at":"2023-10-09T14:07:53.000000Z","two_factor_secret":null,"two_factor_recovery_codes":null,"two_factor_confirmed_at":null,"created_at":"2023-10-09T14:07:53.000000Z","updated_at":"2023-10-09T14:07:53.000000Z","google_id":null,"birthdate":null}

But, if you pass not existing user ID in the URL, then it will give you an exception error as below:

http://localhost:8000/users/10000

it returns a proper JSON response:

No Query Results For Model Error

Fix Issue:

You can fix this issue using ExceptionHandler so, let's update the following file:

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
{
    /**
     * A list of exception types with their corresponding custom log levels.
     *
     * @var array, \Psr\Log\LogLevel::*>

     */
    protected $levels = [
          
    ];
  
    /**
     * A list of the exception types that are not reported.
     *
     * @var array>

     */
    protected $dontReport = [
          
    ];
  
    /**
     * A list of the inputs that are never flashed to the session on validation exceptions.
     *
     * @var array

     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];
    /**
     * Register the exception handling callbacks for the application.
     */
    public function register(): void
    {
        $this->reportable(function (Throwable $e) {
              
        });
    }
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function render($request, Exception|Throwable $e)
    {
        if ($e instanceof ModelNotFoundException) {
            return response()->json(['error' => 'Data not found.']);
        }
  
        return parent::render($request, $e);
    }
}

Now, if you run not existing user ID then it will give you a response like the one below:

http://localhost:8000/users/10000

it returns a proper JSON response:

{"error":"Data not found."}

I hope it can help you...

0 Comments

Leave a Comment