Skip to content

Instantly share code, notes, and snippets.

@devhammed
Created December 4, 2025 09:33
Show Gist options
  • Select an option

  • Save devhammed/2b6f6ab2738a4ecc1c8f3c2e8f2a2269 to your computer and use it in GitHub Desktop.

Select an option

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