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

26-Dec-2023

.

Admin

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

Hello Dev,

In this example, you will learn how to handle the "no query results for model" error in Laravel 10. you'll learn how to handle "no query results for the model. Here you will learn no query results for the model. you'll learn no query results for the model after trying to add. Alright, let’s dive into the steps.

I was working on my RESTful API with a User model when I encountered the following error in the show method: 'No query results for the model [App\User] 1.' Initially, I searched on Google for information about the 'No query results for a model' issue and successfully fixed it. However, I wanted to understand why this error occurs.

We can simply handle the exception and return a better response. To do this, you just need to add the following code to your Handler.php file.

I am going to give you full error so let's understand what I wrote and what the issue I fetched and how to resolve that.

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());

}

}

Error

No query results for model [App\\User] 1

Step 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.

Ezoic

*

* @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...

#Laravel 10