php
45 lines · 8 steps
Caching HTTP responses with Laravel middleware
A middleware that serves cached responses for safe GET requests and stores fresh ones on the way out.
Explained by
highlit
1<?php
2
3namespace App\Http\Middleware;
4
5use Closure;
6use Illuminate\Http\Request;
7use Illuminate\Support\Facades\Cache;
8use Symfony\Component\HttpFoundation\Response;
9
10class CacheResponse
11{
12 public function handle(Request $request, Closure $next, int $ttl = 300): Response
13 {
14 if (! $request->isMethod('GET') || $request->hasHeader('Authorization')) {
15 return $next($request);
16 }
17
18 $key = $this->cacheKey($request);
19
20 if ($cached = Cache::get($key)) {
21 return response($cached['content'], $cached['status'])
22 ->withHeaders($cached['headers'])
23 ->header('X-Cache', 'HIT');
24 }
25
26 $response = $next($request);
27
28 if ($response->isSuccessful()) {
29 Cache::put($key, [
30 'content' => $response->getContent(),
31 'status' => $response->getStatusCode(),
32 'headers' => [
33 'Content-Type' => $response->headers->get('Content-Type'),
34 ],
35 ], now()->addSeconds($ttl));
36 }
37
38 return $response->header('X-Cache', 'MISS');
39 }
40
41 protected function cacheKey(Request $request): string
42 {
43 return 'response:'.sha1($request->fullUrl());
44 }
45}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Only cache idempotent, unauthenticated requests to avoid serving one user's data to another.
- 2An X-Cache header makes it easy to verify hits versus misses in production.
- 3Storing status, content, and headers together lets you faithfully reconstruct a response from cache.
Related explainers
ruby
module RequestTagging class Middleware def initialize(app) @app = app
Per-request context with CurrentAttributes in Rails
middleware
thread-safety
logging
Intermediate
7 steps
php
<?php final class RememberMeCookie {
Signed remember-me cookies in PHP
authentication
hmac
cookies
Intermediate
8 steps
typescript
type Middleware<TIn, TOut> = (ctx: TIn) => Promise<TOut> | TOut; class Pipeline<TIn, TOut> { private constructor(private readonly run: Middleware<TIn, TOut>) {}
A type-safe async middleware pipeline
generics
type-safety
middleware
Advanced
9 steps
go
package middleware import ( "net/http"
Wrapping Gin requests in a DB transaction
middleware
transactions
error-handling
Intermediate
8 steps
python
from django.core.cache import cache from django.core.cache.utils import make_template_fragment_key from django.db.models.signals import post_save, post_delete from django.dispatch import receiver
Busting template fragment caches in Django
caching
signals
cache-invalidation
Intermediate
4 steps
php
<?php namespace App\Validation;
Building a reusable address form validator in PHP
validation
error-accumulation
regex
Intermediate
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/caching-http-responses-with-laravel-middleware-explained-php-0075/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.