forked from alexjustesen/speedtest-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAcceptJsonMiddleware.php
More file actions
38 lines (32 loc) · 1.21 KB
/
AcceptJsonMiddleware.php
File metadata and controls
38 lines (32 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
class AcceptJsonMiddleware
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): SymfonyResponse
{
// Check if the Accept header includes application/json
if (! $request->acceptsJson()) {
return response()->json([
'message' => 'This endpoint only accepts JSON. Please include "Accept: application/json" in your request headers.',
'error' => 'Unsupported Media Type',
], Response::HTTP_NOT_ACCEPTABLE);
}
// Ensure the response is JSON
$response = $next($request);
// Force JSON content type if not already set
if (! $response->headers->has('Content-Type') ||
! str_contains($response->headers->get('Content-Type'), 'application/json')) {
$response->headers->set('Content-Type', 'application/json');
}
return $response;
}
}