Laravel - How to handle "No query results for model" Error

March 14, 2018 | Category : Laravel 5.6 Laravel 5.5 Laravel 5 Laravel PHP

Laravel - How to handle "No query results for model" Error

Yesterday, I was just working on my restful API with User model and I found following error on show method: "No query results for the model [App\\User] 1", first I search on google about No query results for a model issue and fix that. but I want to understand why this error comes. i found why No query results for the model is an error on show, edit and update method when you used a model as a parameter. So basically when you pass id in URL then laravel model will check id is found or not on given model. So it returns ModelNotFoundException exception. we can return as a response.

We can simple handle exception and return a better response. So just we will handle ModelNotFoundException on our Handler.php file. So you need to just add following code to your Handler.php.

I am going to give you full error so let's understand what i write and what is the issue i fetched and how to resolved that.

My Controller Method:

/**

* Display the specified resource.

*

* @param \App\User $user

* @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\Foundation\Exceptions\Handler as ExceptionHandler;

use Illuminate\Database\Eloquent\ModelNotFoundException;


class Handler extends ExceptionHandler

{

/**

* A list of the exception types that are not reported.

*

* @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 you found your best solution....