spatie/laravel-varnish
Integrate Varnish 4/5 with Laravel: add middleware to force-cache selected routes and flush/purge the Varnish cache from within your app. Includes simple configuration and supports Laravel and Lumen.
CacheableByVarnish middleware) is stateless and non-blocking, making it suitable for high-throughput APIs or dynamic content sites where Varnish’s TTL-based caching is desirable.Route::middleware()), HTTP responses, and event system (e.g., CachePurged events), enabling tight integration with existing workflows (e.g., queue-based purges post-model updates).composer require + service provider binding, with zero configuration for basic use. Advanced features (e.g., custom Varnish hosts, ban lists) are optional.Cache-Control and Surrogate-Control headers to enforce Varnish caching, but requires pre-existing knowledge of Varnish’s vcl configuration (e.g., backend definitions, hash logic).ETag-based validation), which may require custom VCL or middleware extensions.vcl rules (e.g., wrong backend definitions, missing hash directives) can lead to silent failures (e.g., cached stale data). The package assumes Varnish is pre-configured correctly.Varnish::purge()) may introduce latency if Varnish is remote or under load.Varnish::purge() to multiple hosts)?X-Cache headers, TTL enforcement)?backend directive pointing to Laravel’s origin (e.g., backend laravel).hash directives for cache keys (e.g., req.url, req.http.X-Cache-Key).vcl_recv/vcl_deliver logic to respect Surrogate-Control headers.X-Forwarded-* headers to Varnish (critical for req.http.host hashing).CacheableByVarnish middleware to a non-critical route (e.g., /docs).Surrogate-Control: max-age=... headers.curl -I shows X-Cache: HIT after refresh.Varnish::purge('/path')) work./assets, /blog)./products) with short TTLs (e.g., 5s) for testing.Cache-Control) with Surrogate-Control for all Varnish-cached routes.saved events, queue-based purges)./products/*).Route::middleware() syntax).ShareHeaders) overrides Cache-Control after CacheableByVarnish.vcl syntax).Surrogate-Control logic may need extension.composer require spatie/laravel-varnish
php artisan vendor:publish --provider="Spatie\Varnish\VarnishServiceProvider" --tag="config"
varnish_host (default: 127.0.0.1:6082).purge_ban_list if using Varnish’s ban mechanism.Route::middleware(['web', 'cacheable.by.varnish'])->group(function () {
// Cached routes
});
Product::saved(function ($product) {
Varnish::purge("/products/{$product->id}");
});
PurgeVarnish::dispatch($url)->delay(now()->addSeconds(10));
How can I help you explore Laravel packages today?