Hi @hmmehead
I think this post will help you, https://laraveldaily.com/laravel-api-404-response-return-json-instead-of-webpage-error/
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I am trying to create a RESTful API using laravel, I'm trying to fetch a resource with an invalid ID, and the result is 404 since it is not found, but my problem is the response is not in JSON format, but a View 404 (by default) with HTML. Is there any way to convert the response into JSON? For this situation, I use Homestead.
I try to include a fallback route, but it does not seem to fit this case.
Route::fallback(function () {
return response()->json(['message' => 'Not Found.'], 404);
});
I try to modify the Handler (App\Exceptions), but nothing change.
public function render($request, Exception $e)
{
if ($e instanceof ModelNotFoundException) {
if ($request->ajax()) {
return response()->toJson([
'message' => 'Not Found.',
], 404);
}
}
return parent::render($request, $e);
}
EDIT***
In addition, I'm using Telescope, and I noticed that the responce is actually presenting "HTML responds" when i try to se a invalid id e.g
I would like to thank everyone for their help. I will summarize some of the things necessary to get the solution of my problem:
1 - Like @audunru said, was necessary change the .env file
2 - In my last answer, there was a conditional parameter ($ request-> wantsJson () )
Please or to participate in this conversation.