I have exposed the API of a laravel 5.7 application. My goal is to return json response for all API calls that results in a 404 error.
This is how I have gone about achieving my goal
I modified the app\Exceptions\Handler.php file like this
// Add this at the top after namespace
use Illuminate\Database\Eloquent\ModelNotFoundException;
// Edited the render method like this
public function render($request, Exception $exception)
{
if ($exception instanceof ModelNotFoundException && $request->wantsJson()) {
return response()->json(['error' => 'Book Not found'], 404);
}
return parent::render($request, $exception);
}
And add a fallback route to routes\api.php file like this
Route::fallback(function(){
return response()->json(['message' => 'Page Not Found'], 404);
});
With this a call to a route that doesn't exist returns this {"message":"Page Not Found"} correctly but a call to localhost:8000/api/books/1 returns the default laravel 404 page which is not the behavior I am looking for.
If i remove && $request->wantsJson() from the render method, both calls made to localhost:8000/books/1 & localhost:8000/api/books/1 return {"error":"Book Not found"}. But this also is not what i want.
Target Behavior:
get localhost:8000/books/1 return default laravle 404 not found page
get localhost:8000/api/books/1 return json response
How can I achieve this?