Getting error illuminate\database\eloquent\modelnotfoundexception: no query results for model such as [App\User], [App\Pruduct], [App\Model\User] etc”, This type of error comes in one situation, which is to get the data from Laravel model and the data is not found in the database. So at that time, returns ModelNotFoundException exception as response.
So note that, To handle exception and return a better response. So just you need to use handle ModelNotFoundException in laravel applications.
How to fix illuminate\database\eloquent\modelnotfoundexception: no query results for model
Suppose, you want to fetch all products from MySQL database using laravel eloquent; as shown below:
<?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(Product $product) { return response()->json($product->toArray()); } }
And you are finding some error like the following:
No query results for model [App\\Product] 1
So visit the app/Exceptions directory of your laravel application and open Handler.php file; Then update the render method of Handler.php file; as shown below:
<?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); } }
Note that, this example tutorial will also work with laravel version.