In this tutorial you will learn about the Laravel 8 How To Handle “No Query Results For Model” Error and its application with practical example.
In this article, I’ll show you how to solve “No Query Results For Model” Error.
Working with restful API in my laravel project with User model I came across following error on show method: “No query results for the model [App\\User] 1”. After lots of effort I came to solution to handle “No Query Results For Model” Error.
Laravel 8 How To Handle “No Query Results For Model” Error
In this article I would like share solution for Handle “No Query Results For Model” Error.
Controller Method :-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?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()); } } |
In this code I am facing error:
1 |
No query results for model [App\\User] 1 |
I handle this error as following:
Handle Exception : app/Exceptions/Handler.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
<?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); } } |