laravel-responsecache

repository·main·Indexed 25 days ago

https://github.com/spatie/laravel-responsecache

A Laravel package that speeds up applications by caching entire HTTP responses for successful GET requests. It provides middleware for standard and flexible caching (with grace periods), customizable cache drivers, and support for custom replacers, cache profiles, hashers, and serializers to handle dynamic content and request identification.

Tokens
14.6K
Snippets
49
Records
84
Agent score
81%

What's inside spatie/laravel-responsecache

  1. Overview of Laravel Response Cache

    main

    This package speeds up Laravel applications by caching entire responses. By default, it caches all successful GET requests that return text-based content (like HTML and JSON) for one week.

    When a request is made for the first time, the package saves the response. Subsequent identical requests return the cached response immediately, bypassing the application logic and significantly improving performance.

  2. Tag cached responses using middleware

    main

    You can assign tags to specific routes using the CacheResponse::for method within your route definitions. This requires a cache driver that supports tags (e.g., Redis or Memcached). Tags allow you to group responses so they can be cleared together later.

    use Spatie\ResponseCache\Middlewares\CacheResponse;
    
    Route::get('/posts', [PostController::class, 'index'])
        ->middleware(CacheResponse::for(minutes(5), tags: ['posts']));
    
    Route::get('/api/posts', [ApiPostController::class, 'index'])
        ->middleware(CacheResponse::for(minutes(5), tags: ['posts', 'api']));
  3. Forget specific URIs

    main

    You can remove specific URIs from the cache using the ResponseCache::forget() method or the Artisan CLI. The forget() method accepts a single string, an array of strings, or multiple string arguments.

    use Spatie\ResponseCache\Facades\ResponseCache;
    
    // Forget one URI
    ResponseCache::forget('/some-uri');
    
    // Forget several URIs
    ResponseCache::forget(['/some-uri', '/other-uri']);
    
    // Or pass them as separate arguments
    ResponseCache::forget('/some-uri', '/other-uri');
    php artisan responsecache:clear --url=/some-uri
  4. Implement standard response caching

    main

    Use the CacheResponse middleware to cache successful GET requests that return text-based content (like HTML or JSON). By default, the package caches responses for a week, but you can specify a custom lifetime using the for() method. Logged-in users receive their own separate cache entries.

    use Spatie\ResponseCache\Middlewares\CacheResponse;
    
    Route::middleware(CacheResponse::for(minutes(10)))->group(function () {
        Route::get('/posts', [PostController::class, 'index']);
        Route::get('/posts/{post}', [PostController::class, 'show']);
    });
  5. Register replacers in configuration

    main

    After creating a custom replacer, you must register its class name in the replacers array within your config/responsecache.php configuration file. This ensures the package executes your replacer during the caching and serving processes.

    // config/responsecache.php
    
    'replacers' => [
        \Spatie\ResponseCache\Replacers\CsrfTokenReplacer::class,
        \App\Replacers\UserNameReplacer::class,
    ],
  6. Use flexible (stale-while-revalidate) caching

    main

    Use FlexibleCacheResponse to serve stale content while refreshing the cache in the background. The response is considered fresh for the duration of lifetime. Once that expires, the stale content is served during the grace period while a background refresh occurs.

    use Spatie\ResponseCache\Middlewares\FlexibleCacheResponse;
    use Carbon\CarbonInterval;
    
    Route::middleware(FlexibleCacheResponse::for(
        lifetime: CarbonInterval::minutes(5),
        grace: CarbonInterval::minute(),
        tags: 'posts',
    ))->group(function () {
        Route::get('/posts', [PostController::class, 'index']);
    });
  7. Clear tagged content

    main

    If you are using cache tags, you can clear only the responses associated with specific tags by passing an array of tag names to ResponseCache::clear().

    use Spatie\ResponseCache\Facades\ResponseCache;
    
    // Clear only responses tagged with 'posts'
    ResponseCache::clear(['posts']);
    
    // Clear responses tagged with both 'foo' and 'bar'
    ResponseCache::clear(['foo', 'bar']);
  8. Use PHP attributes for per-action cache control

    main

    If you have applied CacheResponse or FlexibleCacheResponse middleware to a route, you can use PHP attributes on controller methods for more granular control. Note that attributes require the middleware to be present on the route level to function.

    use Spatie\ResponseCache\Attributes\Cache;
    use Spatie\ResponseCache\Attributes\FlexibleCache;
    use Spatie\ResponseCache\Attributes\NoCache;
    
    class PostController
    {
        // Cache with custom lifetime (seconds) and tags
        #[Cache(lifetime: 600, tags: ['posts'])]
        public function index() { /* ... */ }
    
        // Flexible cache with lifetime and grace (seconds)
        #[FlexibleCache(lifetime: 300, grace: 60, tags: ['posts'])]
        public function popular() { /* ... */ }
    
        // Prevent caching on a specific action
        #[NoCache]
        public function create() { /* ... */ }
    }
  9. Upgrade to Laravel ResponseCache v5.0.0

    main

    In v5.0.0, cache lifetime is defined in seconds rather than minutes. Ensure you update your configuration and middleware calls:

    • Change cache_lifetime_in_minutes to cache_lifetime_in_seconds in your config file.
    • If using cacheResponse middleware, convert the time parameter from minutes to seconds (e.g., value * 60).
    • If extending core classes like CacheResponse or ResponseCacheRepository, ensure relevant methods handle seconds.
  10. Apply cache middleware to routes

    main

    Use the CacheResponse middleware to cache entire HTTP responses. You can use the default lifetime from your configuration, or specify a custom lifetime using CarbonInterval. You can also attach tags to responses for selective clearing later.

    use Spatie
    esponsecache\Middlewares\CacheResponse;
    use Carbon\CarbonInterval;
    
    // Cache with default lifetime (from config)
    Route::middleware(CacheResponse::class)->group(function () {
        Route::get('/posts', [PostController::class, 'index']);
    });
    
    // Cache with custom lifetime using CarbonInterval
    Route::middleware(CacheResponse::for(lifetime: CarbonInterval::minutes(10)))->group(function () {
        Route::get('/posts', [PostController::class, 'index']);
    });
    
    // Cache with tags for selective clearing
    Route::middleware(CacheResponse::for(lifetime: CarbonInterval::hour(), tags: 'posts'))->group(function () {
        Route::get('/posts', [PostController::class, 'index']);
    });