Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Responsecache Laravel Package

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.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require spatie/laravel-responsecache

Publish the config file (optional):

php artisan vendor:publish --provider="Spatie\ResponseCache\ResponseCacheServiceProvider" --tag="responsecache-config"
  1. First Use Case: Apply the middleware to a route group or individual route:

    use Spatie\ResponseCache\Middlewares\CacheResponse;
    
    Route::middleware(CacheResponse::for(minutes(10)))->group(function () {
        Route::get('/posts', [PostController::class, 'index']);
    });
    
    • This caches all successful GET requests returning text-based content (HTML/JSON) for 10 minutes.
  2. Where to Look First:

    • Official Documentation for configuration and advanced usage.
    • config/responsecache.php for default settings (e.g., cache driver, excluded routes, debug headers).
    • app/Http/Middleware/ to inspect middleware behavior or extend it.

Implementation Patterns

Core Workflows

  1. Route-Level Caching:

    • Apply middleware to route groups or individual routes with custom lifetimes:
      Route::middleware(CacheResponse::for(hours(1)))->get('/dashboard', [DashboardController::class, 'index']);
      
    • Use flexible caching for stale-while-revalidate patterns:
      Route::middleware(FlexibleCacheResponse::for(lifetime: hours(1), grace: minutes(5)))->get('/analytics');
      
  2. Controller-Level Attributes (Laravel 8+):

    • Annotate controllers/methods with PHP attributes for declarative caching:
      use Spatie\ResponseCache\Attributes\Cache;
      
      #[Cache(lifetime: '1 hour')]
      public function index() { ... }
      
    • Combine with route middleware for granular control.
  3. Cache Invalidation:

    • Clear cached responses programmatically:
      use Spatie\ResponseCache\Facades\ResponseCache;
      
      ResponseCache::clear(); // Clear all
      ResponseCache::forget('https://example.com/posts/1'); // Clear specific URL
      
    • Tag-based invalidation (requires tags config):
      #[Cache(lifetime: '1 hour', tags: ['posts'])]
      public function index() { ... }
      ResponseCache::clearTags(['posts']); // Invalidate all tagged responses
      
  4. Conditional Caching:

    • Exclude routes/paths from caching in config/responsecache.php:
      'excluded_paths' => [
          'admin/*',
          'api/*',
      ],
      
    • Use #[NoCache] attribute to opt-out specific methods:
      use Spatie\ResponseCache\Attributes\NoCache;
      
      #[NoCache]
      public function sensitiveData() { ... }
      
  5. Debugging & Monitoring:

    • Enable debug headers to inspect cache hits/misses:
      'debug_headers' => env('APP_ENV') !== 'production',
      
    • Check headers like X-Response-Cache (HIT, MISS, STALE).
  6. Integration with Other Packages:

    • Laravel Horizon: Schedule cache clearing during off-peak hours.
    • Laravel Echo/Pusher: Invalidate cache on real-time events (e.g., CacheMissedEvent listeners).
    • Laravel Scout: Cache search results with CacheResponse middleware.

Gotchas and Tips

Pitfalls

  1. Cache Key Collisions:

    • Issue: Different URLs with identical content may collide if not hashed properly.
    • Fix: Use CacheResponse::using() to customize the hasher (e.g., xxh128 for speed):
      Route::middleware(CacheResponse::using('xxh128')->for(minutes(10)))->get('/search');
      
  2. State Sharing in Middleware:

    • Issue: Middleware instances may not share state between handle() and terminate().
    • Fix: Use request attributes to store state (fixed in v8.3.1+):
      $request->attributes->add(['cache_state' => $state]);
      
  3. Post-Response Modifications:

    • Issue: Middleware may cache responses before post-response logic (e.g., AppServiceProvider@finishRequest).
    • Fix: Defer cache storage to terminate() (default in v8.3.0+):
      'defer_cache_storage' => true, // config/responsecache.php
      
  4. Race Conditions:

    • Issue: null cache values may cause race conditions between has() and get().
    • Fix: Treat null as a cache miss (fixed in v8.4.0).
  5. CSRF Tokens in Cached Responses:

    • Issue: CSRF tokens in cached HTML forms may invalidate responses.
    • Fix: Use CsrfTokenReplacer (enabled by default) to dynamically replace tokens:
      'csrf_token_replacer' => true, // config/responsecache.php
      
  6. Flexible Cache Grace Periods:

    • Issue: Stale responses may linger longer than expected.
    • Fix: Monitor X-Response-Cache-Stale headers and adjust grace periods:
      FlexibleCacheResponse::for(lifetime: hours(1), grace: minutes(10));
      
  7. Tag-Based Invalidation:

    • Issue: Tags may not invalidate all expected responses.
    • Fix: Ensure consistent tag usage across controllers and clear tags explicitly:
      ResponseCache::clearTags(['posts', 'users']);
      

Debugging Tips

  1. Inspect Headers:

    • Check X-Response-Cache, X-Response-Cache-Tags, and X-Response-Cache-Stale in browser dev tools.
  2. Log Cache Events:

    • Listen to events for debugging:
      use Spatie\ResponseCache\Events\CacheMissed;
      
      CacheMissed::subscribe(function (CacheMissed $event) {
          Log::info('Cache missed for:', $event->url);
      });
      
  3. Disable Caching Temporarily:

    • Override middleware in app/Http/Kernel.php:
      protected $middlewareGroups = [
          'web' => [
              // ... other middleware
              // \Spatie\ResponseCache\Middlewares\CacheResponse::class, // Comment out
          ],
      ];
      
  4. Clear Cache Strategically:

    • Use ResponseCache::forget() with URL patterns:
      ResponseCache::forget('https://example.com/posts/*'); // Clear all posts
      

Extension Points

  1. Custom Cache Drivers:

    • Implement Spatie\ResponseCache\CacheProfiles\CacheProfile for custom storage (e.g., Redis, DynamoDB).
  2. Middleware Decorators:

    • Extend CacheResponse or FlexibleCacheResponse to add logic:
      use Spatie\ResponseCache\Middlewares\CacheResponse;
      
      class CustomCacheResponse extends CacheResponse {
          public function handle($request, Closure $next) {
              // Pre-process request
              $response = parent::handle($request, $next);
              // Post-process response
              return $response;
          }
      }
      
  3. Attribute Interceptors:

    • Override attribute behavior by binding your own resolver:
      ResponseCache::extend('custom', function () {
          return CacheResponse::using('xxh128')->for(minutes(30));
      });
      
  4. Event Listeners:

    • React to cache misses/stales for analytics or notifications:
      CacheMissed::subscribe(function ($event) {
          // Send alert or log
      });
      
  5. Cache Key Customization:

    • Override the default key generation:
      CacheResponse::using()->for(minutes(10))->withKey(function ($request) {
          return md5($request->fullUrl() . $request->user()?->id);
      });
      

Configuration Quirks

  1. Cache Driver:

    • Defaults to file. For production, use redis or database:
      'cache_driver' => env('CACHE_DRIVER', 'redis'),
      
  2. Excluded Paths:

    • Use regex or glob patterns:
      'excluded_paths' => [
          'healthcheck',
          'api/*',
          'admin/*',
          'webhooks/*',
      ],
      
  3. Debug Headers:

    • Disable in production:
      'debug_headers' => app()->environment('local'),
      
  4. Cache Lifetime:

    • Ensure values are integers (avoid floats):
      CacheResponse::for(seconds(3600)) // 1 hour (integer)
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai