In this short article, we will learn how we can handle “No Query Results For Model” error in Laravel. First of all, we need to understand why this error occurred. Then, we will write a exception handling for this error.
When we query database using findOrFail
or firstOrFail
methods, we may encounter this error. This is because no result has been found for the given query. So, it throws an exception. We must handle this exception to display a nice message in the frontend (or API).
Let’s look at the example while querying the record from our controller file.
<?php
//controller file
.........
public function show($id)
{
try {
$article = Article::findOrFail($id)
return response()->json(['status' => 200, 'data' => $article]);
} catch (Exception $e) {
return response()->json(['status' => 400, 'message' => $e->getMessage()]);
}
}
In the example above, We are quering database with findOrFail($id)
. So, if the record is not found, it will throw an exception with message No query results for Model
. Although it doesn’t cause any issue, but it’s always best not to any internal details such as table names, models, to the end user. Thus, we need to display our custom message instead.
So, how can we achieve that? Well, it’s simple and straightforward. We need to catch the exception in our exception handler. There is a Handler.php
file inside app/Exceptions
directory. In this handler class, add a new method render()
if there isn’t any. So, our final Handler class looks like below.
<?php
//app/Exceptions/Handler.php
namespace App\Exceptions;
use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Database\Eloquent\ModelNotFoundException;
class Handler extends ExceptionHandler
{
..............
/**
* 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' => 'Record not found.']);
}
return parent::render($request, $exception);
}
}
Inside render method, we check if the exception is an instance of ModelNotFoundException
class, then we return the json
response with Record not found
message. That is all. Now, everytime when a record is not found, it will automatically catch the exception and our custom message is returned.
What are your thoughts? Don’t forget to drop your comments below.
Thank you for this article. I was searching for this issue.