How To Handle No Query Results For Model in Laravel 10 - TechvBlogs

How To Handle No Query Results For Model in Laravel 10

Learn how to gracefully handle empty query results in Laravel 10 with expert tips and best practices.


Smit Pipaliya - Author - TechvBlogs
Smit Pipaliya
 

5 months ago

TechvBlogs - Google News

In this article, we'll illustrate how to handle the 'No Query Results for Model' exception in Laravel 10. If you've encountered the 'No Query Results for Model' error in Laravel and are seeking a solution, you've come to the right place. We'll provide a straightforward example of how to catch and resolve the 'No Query Results for Model' issue in Laravel. Read on to learn how to effectively address this common challenge in Laravel development.

In the Laravel framework, encountering the 'No query results for model' exception is a commonplace scenario. This exception arises when you attempt to retrieve a database record using Eloquent, Laravel's integrated Object-Relational Mapping (ORM), but the system fails to locate a corresponding entry. Discover how Laravel employs this exception as a useful mechanism for addressing such occurrences.

Get ready for a straightforward solution to resolve this issue with the help of ModelNotFoundException. Let's dive into this easy-to-implement fix.

In Controller:

You'll find the following code snippet in your user controller:

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, when you pass the correct and existing user ID in the URL, everything functions as expected, just as shown below:

http://localhost:8000/users/1

It will return the expected JSON response

{
  "id": 1,
  "name": "TechvBlogs",
  "email": "[email protected]",
  "email_verified_at": "2023-10-25T09:53:23.000000Z",
  "created_at": "2023-10-25T09:53:23.000000Z",
  "updated_at": "2023-10-25T09:53:23.000000Z",
}

However, when an invalid or non-existent user ID is provided in the URL, it triggers an exception error, as demonstrated below:

http://localhost:8000/users/100

In this scenario, it returns a valid JSON response:

No Query Results For Model Error

Fix this Issue:

To resolve this issue, you can make the necessary fixes by updating 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, when you attempt to run with a non-existing user ID, you will receive a response as illustrated below:

http://localhost:8000/users/100

It will return the expected JSON response

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

Thank you for reading this blog.

Read Also: How to Increase max_connections in MySQL

If you want to manage your VPS / VM Server without touching the command line go and  Checkout this linkServerAvatar allows you to quickly set up WordPress or Custom PHP websites on VPS / VM in a  matter of minutes.  You can host multiple websites on a single VPS / VM, configure SSL certificates, and monitor the health of your server without ever touching the command line interface.

If you have any queries or doubts about this topic please feel free to contact us. We will try to reach you.

Comments (0)

Comment


Note: All Input Fields are required.