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:

    composer require spatie/laravel-responsecache
    

    Publish the config file (optional):

    php artisan vendor:publish --provider="Spatie\ResponseCache\ResponseCacheServiceProvider" --tag="responsecache-config"
    
  2. First Use Case: Cache a route for 10 minutes using middleware:

    use Spatie\ResponseCache\Middlewares\CacheResponse;
    
    Route::middleware(CacheResponse::for(minutes(10)))->group(function () {
        Route::get('/posts', [PostController::class, 'index']);
    });
    
  3. Key Files to Review:

    • config/responsecache.php (for global settings)
    • app/Http/Middleware/ (for custom middleware extensions)
    • app/Providers/AppServiceProvider.php (for global cache configuration)

Implementation Patterns

Core Workflows

  1. Route-Level Caching:

    // Cache for 1 hour with tags (for cache invalidation)
    Route::middleware(CacheResponse::for(hours(1), tags: ['posts']))
         ->get('/posts', [PostController::class, 'index']);
    
  2. Controller-Level Attributes (Laravel 8.43+):

    use Spatie\ResponseCache\Attributes\Cache;
    
    #[Cache(lifetime: '1 hour', tags: ['dashboard'])]
    public function index() { ... }
    
  3. Flexible Caching (Stale-While-Revalidate):

    use Spatie\ResponseCache\Middlewares\FlexibleCacheResponse;
    
    Route::get('/dashboard', [DashboardController::class, 'index'])
         ->middleware(FlexibleCacheResponse::for(
             lifetime: hours(1),
             grace: minutes(5)
         ));
    
  4. Global Cache Configuration:

    // In AppServiceProvider boot()
    ResponseCache::shareCacheBetweenRequests();
    ResponseCache::enableDebugHeaders();
    

Integration Tips

  • Cache Invalidation: Use tags to invalidate related caches:

    ResponseCache::forgetTags(['posts']); // Invalidate all 'posts' tagged caches
    
  • Conditional Caching: Skip caching for authenticated users:

    Route::middleware([
        'auth',
        CacheResponse::for(minutes(10))->unless(fn ($request) => $request->user()->isAdmin())
    ])->get('/profile');
    
  • API Responses: Cache JSON responses with CacheResponse::forApi():

    Route::middleware(CacheResponse::forApi(minutes(5)))->get('/api/posts');
    
  • Event-Based Cache Clearing: Listen to CacheMissed events to log cache misses:

    event(new CacheMissed($request, $response));
    

Gotchas and Tips

Common Pitfalls

  1. Race Conditions:

    • Use shareCacheBetweenRequests() to avoid state issues in middleware.
    • Prefer FlexibleCacheResponse for high-traffic endpoints to avoid stale data during cache refreshes.
  2. CSRF Tokens:

    • Cached responses may break CSRF protection. Use CsrfTokenReplacer:
      ResponseCache::replaceCsrfTokenInCachedResponses();
      
  3. Dynamic Content:

    • Avoid caching routes with dynamic data (e.g., user-specific content). Use unless():
      CacheResponse::for(minutes(10))->unless(fn ($request) => $request->user()->hasDynamicContent())
      
  4. Debugging:

    • Enable debug headers to inspect cache status:
      ResponseCache::enableDebugHeaders();
      
    • Check headers like X-Response-Cache (HIT, MISS, STALE).
  5. Memory Usage:

    • Monitor cache storage (default: file). For large-scale apps, use Redis:
      ResponseCache::useRedis();
      

Pro Tips

  • Tag-Based Invalidation: Use tags for related resources (e.g., ['posts', 'categories']) to invalidate caches when data changes:

    ResponseCache::forgetTags(['posts']); // After updating a post
    
  • Partial Caching: Cache only specific parts of a response using CacheResponse::forPartial() (requires manual implementation).

  • Testing: Mock the cache in tests:

    $this->actingAs($user)
         ->withGlobalCacheDisabled()
         ->get('/cached-route');
    
  • Performance Tuning:

    • Use xxh128 hasher (default) for faster cache key generation.
    • Adjust cache_lifetime in config/responsecache.php for global defaults.
  • Edge Cases:

    • Redirects: Caching redirects may cause loops. Exclude them:
      CacheResponse::for(minutes(10))->except(fn ($request) => $request->is('redirects/*'));
      
    • WebSockets: Disable caching for WebSocket routes.
  • Custom Storage: Extend the cache driver:

    ResponseCache::useCustomStorage(function () {
        return Cache::store('redis')->rememberForever(...);
    });
    
  • Laravel 11+: Use attributes for cleaner code:

    #[Cache(lifetime: '1 hour', tags: ['homepage'])]
    public function show() { ... }
    
  • Cache Profiling: Use ResponseCache::profile() to log cache hits/misses:

    ResponseCache::profile();
    
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony