Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

hmmehead's avatar

Laravel API returns a view 404 error instead of JSON error

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

0 likes
9 replies
hmmehead's avatar

At this moment, i solved my problem with this code, into the handler:

    public function render($request, Exception $exception)
    {
        if ($exception instanceof ModelNotFoundException) {
            return response()->json([
                'message' => 'Not Found!',
            ], 404);
        }
        return parent::render($request, $exception);
    }

could it be, the "best" solution?

audunru's avatar

When you make your request, are you using the "Accept: application/json" HTTP Header?

hmmehead's avatar

@AUDUNRU - I tried to use it a few times though, it was not appearing in the body of the requisition. How I use the telescope, I was able to visualize. I also noticed that even using this solution, at no time does the "application / json" appear. These are the information that appears


{
cookie: "XDEBUG_TRACE=XDEBUG_ECLIPSE",
accept-encoding: "gzip, deflate, br",
accept: "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
user-agent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36",
upgrade-insecure-requests: "1",
cache-control: "max-age=0",
content-length: "",
content-type: ""
}


audunru's avatar

Just tested with the app I'm working on right now, and without Accept: application/json in the request, I'm getting HTML back when there's an error.

This is the latest version of Laravel (5.8.20), nothing special in the controllers or Handler.php to check if the request wants json or not. So I think you should check with Postman or something similar if you're getting JSON errors back when you request JSON.

HTML:

https://i.imgur.com/oWXnhRh.png

JSON:

https://i.imgur.com/3irKyc8.png

hmmehead's avatar

@AUDUNRU - I cleaned my handler, tried what you asked for and got different errors. For the record, I removed the solution I mentioned in the post above. My laravel version is 5.8 too.

If the headers have Accept, the error that appears is regarding not finding the Model class (What I imagine is solvable with ModelNotFoundException, as I was using),

otherwise, it returns the View 404

audunru's avatar

You probably have debug set to true, you should try with it set to false if you want to see what error you would get in production. It’s in the environment file (though I guess you knew that). :-)

hmmehead's avatar
hmmehead
OP
Best Answer
Level 8

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

1 like

Please or to participate in this conversation.