php
23 lines · 5 steps
Enforcing a JSON Accept header in Laravel
A Laravel middleware that rejects clients that won't accept JSON and normalizes the Accept header for the rest.
Explained by
highlit
1<?php
2
3namespace App\Http\Middleware;
4
5use Closure;
6use Illuminate\Http\Request;
7use Symfony\Component\HttpFoundation\Response;
8
9class EnsureJsonAcceptHeader
10{
11 public function handle(Request $request, Closure $next): Response
12 {
13 if (! $request->accepts(['application/json', 'application/vnd.api+json'])) {
14 return response()->json([
15 'message' => 'This endpoint only serves JSON. Set the Accept header to application/json.',
16 ], Response::HTTP_NOT_ACCEPTABLE);
17 }
18
19 $request->headers->set('Accept', 'application/json');
20
21 return $next($request);
22 }
23}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Middleware lets you guard requests before they reach a controller, centralizing cross-cutting concerns like content negotiation.
- 2Rejecting unacceptable requests with 406 Not Acceptable keeps an API honest about what it actually serves.
- 3Normalizing the Accept header downstream ensures the rest of the stack behaves consistently regardless of what the client sent.
Related explainers
javascript
const ROLE_PERMISSIONS = { admin: ['users:read', 'users:write', 'billing:read', 'billing:write'], manager: ['users:read', 'billing:read'], member: ['users:read'],
Role-based permissions middleware in Express
authorization
middleware
rbac
Intermediate
9 steps
php
<?php namespace App\Console\Commands;
Releasing stale document locks in Laravel
artisan-command
transactions
row-locking
Intermediate
6 steps
php
<?php namespace App\Providers;
Subdomain multi-tenancy routing in Laravel
multi-tenancy
service-container
route-binding
Advanced
7 steps
ruby
module Paginatable extend ActiveSupport::Concern private
A reusable pagination concern in Rails
pagination
concerns
http-headers
Intermediate
8 steps
php
<?php namespace App\Broadcasting;
Authorizing presence channels in Laravel
broadcasting
authorization
presence-channels
Intermediate
3 steps
javascript
const express = require('express'); const app = express(); app.get('/health', (req, res) => res.json({ status: 'ok' }));
Graceful shutdown in an Express server
graceful-shutdown
signal-handling
connection-tracking
Advanced
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/enforcing-a-json-accept-header-in-laravel-explained-php-efa5/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.