Created
December 4, 2025 09:33
-
-
Save devhammed/2b6f6ab2738a4ecc1c8f3c2e8f2a2269 to your computer and use it in GitHub Desktop.
Laravel Content Negotiator Middleware (e.g. /glossaries for HTML & /glossaries.json for JSON)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| namespace App\Http\Middleware; | |
| use Closure; | |
| use Illuminate\Http\Request; | |
| use Symfony\Component\HttpFoundation\Response; | |
| class ContentNegotiator | |
| { | |
| public static array $suffixes = [ | |
| '.json' => 'application/json', | |
| ]; | |
| public function handle(Request &$request, Closure $next): Response | |
| { | |
| $path = $request->path(); | |
| $format = null; | |
| foreach (static::$suffixes as $suffix => $acceptType) { | |
| if (str_ends_with($path, $format)) { | |
| $format = [$suffix, $acceptType]; | |
| break; | |
| } | |
| } | |
| if ($format) { | |
| [$suffix, $acceptType] = $format; | |
| $request->headers->set('Accept', $acceptType); | |
| $request->server->set('REQUEST_URI', substr($path, 0, -strlen($suffix))); | |
| $request = $request->duplicate(); | |
| } | |
| return $next($request); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment