method() !== 'POST') { return $next($request); } $key = $request->header('Idempotency-Key'); if (! $key) { return $next($request); } $cacheKey = 'idempotency:' . hash('sha256', $key); // Return cached response if exists $cached = Cache::get($cacheKey); if ($cached) { return response()->json($cached['body'], $cached['status']) ->header('X-Idempotency-Replayed', 'true'); } $response = $next($request); // Cache successful responses for 24h if ($response->status() < 500) { Cache::put($cacheKey, [ 'body' => json_decode($response->getContent(), true), 'status' => $response->status(), ], 86400); } return $response; } }