Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

Why 404 Page? Setting Correct Headers

Premium
3:49

In this lesson, we will set one correct header value to avoid returning web pages instead of JSON results.


As you can see in the /api/categories/1, we see data for one category.

But what happens if we pass a missing category? We get an HTML page.

But for API, it is wrong. API expects the result as a JSON. In your client, set the headers to Accept -> application/json. Now Laravel knows to send the result as a JSON.

Another way is to set headers using Middleware. First, let's create a Middleware.

php artisan make:middleware AlwaysAcceptJson

Inside Middleware, we have a Request. Middleware is not just for preventing something; you can also add something...

The Full Lesson is Only for Premium Members

Want to access all of our courses? (31 h 16 min)

You also get:

55 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

D
desplega ✓ Link copied!

It may be worth adding the reason why the reportable method needs to be changed by the renderable one. In Laravel the report method is for logging or reporting exceptions, while the render method is for customizing the response sent back to the user when an exception occurs. By separating these concerns, Laravel allows you to handle exceptions in a flexible and organized manner.

D
donilearn ✓ Link copied!

return response()->json(['message' => env('APP_DEBUG')? $e->getMessage() : 'Object not found'], 404);

Just use this

M
Maru ✓ Link copied!

@donilearn Thanks for a good snippet.

    $exceptions->renderable(function (NotFoundHttpException $e, Request $request) {
        if ($request->wantsJson() && !config('app.debug')) {
            return response()->json(['message' => 'Object not found'], 404);
        }
    });

I think this code is little better. It achieves accessing env from config and getting full error stack.

C
CONSTANTlNE ✓ Link copied!

But we set middleware to always set headers application/json so if ($request->wantsJson()) kinda loses its purpose and if we remove middleware and user wont set header during api request , he will still get html... im a beginner and little bit confused.. but ill figure out something

A
AndersonRioba ✓ Link copied!

For me, I normally use 'unauthorized' when in production and leave to not found in development

  • ->withExceptions(function (Exceptions $exceptions): void { $isProduction = app()->isProduction(); $exceptions->render(function (Throwable $e) use ($isProduction) { if ($e instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) { $statusCode = $isProduction ? 401 : 404;

             return response()->json([
                 'message' => $isProduction ? 'Unauthorized' : 'Resource not found.',
                 'error' => $isProduction ? 'Unauthorized' : $e->getMessage(),
             ], $statusCode);
         }