4 months ago

Laravel API returns a view 404 error instead of JSON error

Posted 4 months ago by hmmehead

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);


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

Please sign in or create an account to participate in this conversation.