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

Technical Evaluation

Architecture Fit

  • Highly Complementary to Laravel Ecosystem: The package is purpose-built for Laravel, leveraging its middleware stack, HTTP lifecycle, and caching abstractions (e.g., Cache facade). It integrates seamlessly with Laravel’s routing, middleware groups, and response handling, reducing architectural friction.
  • Stateless Design: Uses request-based caching (via middleware) rather than application-level state, aligning with Laravel’s stateless HTTP philosophy. Cache keys are derived from request attributes (e.g., URI, headers), ensuring consistency.
  • Extensibility: Supports custom cache stores (e.g., Redis, database) via Laravel’s Cache contract, allowing alignment with existing infrastructure. Middleware can be chained or overridden for granular control.
  • Performance-Centric: Optimized for low-latency responses by deferring cache writes to the terminate() phase (post-response), minimizing blocking operations during request processing.

Integration Feasibility

  • Minimal Boilerplate: Requires only middleware registration (e.g., CacheResponse::for()) or PHP attributes (#[Cache]), with zero changes to core Laravel logic. Example:
    Route::middleware(CacheResponse::for(minutes(10)))->group(...);
    
  • Backward Compatibility: Supports Laravel 12+ and PHP 8.4+, with deprecation paths for older versions. No breaking changes to Laravel’s HTTP stack (e.g., no monkeypatching).
  • Tooling Alignment: Works with Laravel’s built-in Cache facade, Artisan commands (e.g., cache:clear), and debugging tools (e.g., dd() for cache inspection). Compatible with Laravel Forge/Vapor for deployment.

Technical Risk

  • Cache Invalidation Complexity:
    • Risk: Stale data if cache invalidation isn’t synchronized with business logic (e.g., model updates). The package provides tags (CacheResponse::for()->withTags()) but requires discipline in tagging strategies.
    • Mitigation: Use FlexibleCacheResponse for grace periods or implement event listeners (e.g., CacheMissedEvent) to trigger recache on data changes.
  • Edge Cases:
    • Dynamic Content: Caching responses with CSRF tokens, user-specific data, or non-deterministic headers (e.g., X-Requested-With) may require middleware tweaks (e.g., CsrfTokenReplacer).
    • Large Responses: Binary data (e.g., PDFs) or responses >1MB may bloat cache storage. Monitor cache size with spatie/laravel-responsecache:clear or Cache::storeSize().
  • Testing Overhead:
    • Risk: Cached responses bypass application logic, complicating unit/integration tests. Mocking middleware or using CacheResponse::disable() in tests is necessary.
    • Mitigation: Use CacheResponse::for()->unless() to exclude test routes or leverage Laravel’s HttpTests trait.

Key Questions

  1. Cache Store Selection:
    • Is Redis/APCu/DynamoDB preferred over file-based caching? The package supports all Laravel cache drivers, but performance/scalability may vary.
  2. Tagging Strategy:
    • How will cache tags align with business entities (e.g., posts:123)? Over-tagging increases cache misses; under-tagging risks stale data.
  3. Flexible Caching Trade-offs:
    • For FlexibleCacheResponse, what grace periods balance staleness vs. recache latency? Monitor CacheMissedEvent frequency.
  4. Monitoring:
    • Are metrics needed for cache hit/miss ratios, storage usage, or recache latency? Extend with Laravel Prometheus or custom logging.
  5. Deployment Impact:
    • How will cache invalidation scale in multi-region deployments? Consider distributed cache invalidation (e.g., Redis pub/sub).

Integration Approach

Stack Fit

  • Laravel-Centric: Designed for Laravel’s middleware pipeline, HTTP lifecycle, and caching abstractions. No conflicts with existing Laravel packages (e.g., laravel/framework, spatie/laravel-permission).
  • PHP Version Support: Requires PHP 8.4+ (Laravel 12+). If using older versions, assess deprecation risks or fork the package.
  • Cache Backend Agnostic: Works with any Laravel cache driver (file, Redis, database), but performance varies:
    • Redis: Best for distributed systems (low latency, pub/sub for invalidation).
    • File: Simplest but not scalable for high traffic.
    • Database: Overkill for most use cases; use only if cache is already DB-backed.

Migration Path

  1. Assessment Phase:
    • Audit routes/controllers to identify cacheable endpoints (e.g., static pages, API responses with GET semantics).
    • Exclude dynamic routes (e.g., user dashboards, real-time data) or use #[NoCache] attributes.
  2. Pilot Deployment:
    • Start with non-critical routes (e.g., /about, /blog) using CacheResponse::for(hours(1)).
    • Monitor cache hit ratios via CacheMissedEvent or custom logging.
  3. Gradual Rollout:
    • Apply caching to middleware groups (e.g., web group for HTML, api for JSON).
    • Use FlexibleCacheResponse for dashboards where staleness is acceptable.
  4. Validation:
    • Verify no regressions in functionality (e.g., CSRF tokens, auth checks).
    • Test edge cases (e.g., concurrent requests, cache store failures).

Compatibility

  • Middleware Conflicts:
    • Order matters: Place CacheResponse after auth/middleware that modifies the request (e.g., VerifyCsrfToken) but before middleware that alters the response (e.g., AppendsAuthLastActiveAt).
    • Example:
      $middleware = [
          \App\Http\Middleware\VerifyCsrfToken::class,
          \Spatie\ResponseCache\Middlewares\CacheResponse::for(minutes(10)),
          \App\Http\Middleware\AppendAuthLastActiveAt::class,
      ];
      
  • Package Dependencies:
    • No hard dependencies beyond Laravel. Soft dependencies (e.g., spatie/php-attribute-reader) are optional for attribute-based caching.
  • Laravel Features:
    • Compatible with:
      • API Resources (JsonResource).
      • Livewire/Inertia (cache entire page responses).
      • Queues (cache generation can be deferred if using terminate() logic).
    • Incompatible:
      • Streaming responses (e.g., SSE, chunked downloads).
      • Responses with Cache-Control: no-store.

Sequencing

  1. Pre-requisites:
    • Laravel 12+ and PHP 8.4+ (or backport to older versions if necessary).
    • Configure a cache driver (Redis recommended for production).
  2. Installation:
    composer require spatie/laravel-responsecache
    php artisan vendor:publish --provider="Spatie\ResponseCache\ResponseCacheServiceProvider"
    
  3. Configuration:
    • Set default cache lifetime in config/response-cache.php:
      'default_lifetime_in_seconds' => 60 * 60, // 1 hour
      
    • Configure cache store (e.g., Redis) in .env:
      CACHE_DRIVER=redis
      
  4. Implementation:
    • Option A: Middleware (route/group level):
      Route::middleware(CacheResponse::for(minutes(10)))->group(function () {
          Route::get('/posts', [PostController::class, 'index']);
      });
      
    • Option B: Attributes (controller/action level):
      #[Cache(lifetime: '10 minutes')]
      public function index() { ... }
      
    • Option C: Global caching (all GET routes):
      $middleware = [
          \Spatie\ResponseCache\Middlewares\CacheResponse::for(minutes(10)),
      ];
      
  5. Post-Deployment:
    • Clear existing cache:
      php artisan cache:clear
      php artisan response-cache:clear
      
    • Monitor cache performance and adjust lifetimes/tags as needed.

Operational Impact

Maintenance

  • Cache Management:
    • Manual Clearing: Use ResponseCache::clear() or Artisan commands:
      php artisan response-cache:clear
      php artisan response-cache:clear --tags=posts
      
    • Automated Invalidation: Implement listeners for model events (e.g., PostUpdated) to clear tags:
      Post::updated(function ($post) {
          ResponseCache::clearTags(['posts:'.$post->id]);
      });
      
    • Tagging Discipline: Enforce naming conventions (e.g., entity:action:id) to avoid tag sprawl.
  • Configuration Drift:
    • Centralize cache lifetimes in config/response-cache.php to avoid hardcoded values in routes/controllers.
    • Use environment variables for dynamic lifet
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.
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
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata