In this article, I'll show you how to handle the "No query results for model" exception in Laravel 10. If you're dealing with this error and need a straightforward solution, you're in the right place. I'll explain how to catch and fix this exception using ModelNotFoundException
.
In Laravel, the "No query results for model" exception happens when you try to get a record from the database using Eloquent (Laravel's built-in ORM) and no matching record is found. Laravel throws this exception to manage such situations.
Here's the controller code:
app/Http/Controllers/UserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
public function show(User $user)
{
return response()->json($user->toArray());
}
}
If you pass an existing user ID in the URL, it works fine.
It returns a proper JSON response:
{
"id": 1,
"name": "User",
"email": "[email protected]",
"type": 0,
"email_verified_at": "2024-07-28T14:13:37.000000Z",
"two_factor_secret": null,
"two_factor_recovery_codes": null,
"two_factor_confirmed_at": null,
"created_at": "2024-07-28T14:13:37.000000Z",
"updated_at": "2024-07-28T14:13:37.000000Z",
"google_id": null,
"birthdate": null
}
But if you pass a non-existing user ID, you'll get an exception:
http://localhost:8000/users/1234
It returns:
No Query Results For Model Error
To fix this, update the ExceptionHandler
:
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
{
protected $levels = [];
protected $dontReport = [];
protected $dontFlash = [
'current_password',
'password',
'password_confirmation',
];
public function register(): void
{
$this->reportable(function (Throwable $e) {
//
});
}
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 try a non-existing user ID, you'll get a proper JSON response.
It returns like this:
{
"error": "Data not found."
}
You might also like:
- Read Also: How to use Algolia search in Laravel 10
- Read Also: Customize Validation Error Message in Laravel 10
- Read Also: How to Get Random Record in Laravel 10 Example
- Read Also: Laravel 10 Restrict User Access From IP Address