spatie/laravel-responsecache
Cache full Laravel responses to speed up your app. Automatically caches successful text-based GET requests (HTML/JSON), with easy middleware per route, configurable lifetimes, and optional stale-while-revalidate “grace” caching to refresh in the background.
CacheResponse as a middleware).#[NoCache] or middleware exclusion.App\Http\Kernel) or selectively (route groups/controllers).CacheMissed, CacheStored) for custom logic (e.g., analytics, logging).| Risk Area | Assessment | Mitigation |
|---|---|---|
| Cache Invalidation | Risk of stale data if business logic changes but cache isn’t invalidated. | Use tags (CacheResponse::for()->withTags()) or manual invalidation (ResponseCache::forget()). |
| Performance Overhead | Initial cache generation may slow first requests. | Use flexible caching for high-traffic endpoints or short TTLs for dynamic content. |
| CSRF/Session Issues | Cached responses may break CSRF tokens or session-dependent content. | Exclude routes with #[NoCache] or use CsrfTokenReplacer middleware. |
| Cache Key Collisions | Custom cache keys may conflict with default hashing. | Use explicit cache keys or debug with X-Response-Cache headers. |
| Testing Complexity | Cached responses complicate unit/integration tests. | Use ResponseCache::clear() in tests or mock the middleware. |
| Dependency Bloat | Adds ~50KB to vendor size (minimal impact). | Negligible for most applications. |
/posts/{id}) that require custom key generation?user:123)?| Phase | Action Items | Dependencies |
|---|---|---|
| Assessment | Audit routes/controllers for cache eligibility (GET, text-based responses). | Analytics data (e.g., slowest endpoints). |
| Pilot | Apply caching to low-risk routes (e.g., static pages, public APIs). | Monitoring (cache hit/miss rates). |
| Gradual Rollout | Expand to high-traffic routes (e.g., product listings, dashboards). | Feature flags for A/B testing. |
| Optimization | Tune TTLs, tags, and flexible caching based on performance data. | Load testing. |
| Global Enable | Apply default caching middleware to App\Http\Kernel. |
Review exclusion rules. |
CacheResponse after middleware that modifies responses (e.g., AppendsAuthToken).laravel-permission).laravel-activitylog).composer require spatie/laravel-responsecache.php artisan vendor:publish --provider="Spatie\ResponseCache\ResponseCacheServiceProvider".CacheResponse::for(seconds(10)) for quick iteration.X-Response-Cache headers in responses.CacheMissed events and adjust invalidation logic.user:123) or manually (ResponseCache::forget()).artisan schedule) to clear stale cache.X-Response-Cache headers to diagnose misses/hits.CacheMissedEvent for troubleshooting.#[NoCache] or use CsrfTokenReplacer.tideways/xhprof or Blackfire.#[Cache] attributes vs. middleware.How can I help you explore Laravel packages today?