Level 104
You can check if the incoming request wants/expects a JSON response using:
if (request()->wantsJson()) {
return response()->json(['message' => 'Not Found'], 404);
}
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi!
I am working on an API. We use the same Laravel installation for the website and the API, but for the API we use an API namespace. I want to return a JSON response for the API if the route is not existing.
With Route::fallback() I can return a 404. But if the if route does exists but they are not using the right resource, it returns a MethodNotAllowedHttpException. I want to change this exception to my own JSON response. How can I do this without affecting the website (only the API)?
You can check if the incoming request wants/expects a JSON response using:
if (request()->wantsJson()) {
return response()->json(['message' => 'Not Found'], 404);
}
Please or to participate in this conversation.