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 Httpcache Laravel Package

barryvdh/laravel-httpcache

Adds HTTP caching to Laravel using Symfony HttpCache. Supports reverse proxy-style caching, cache invalidation, and ESI, helping you speed up responses while keeping dynamic content fresh with simple middleware and configuration.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require barryvdh/laravel-httpcache
    

    Publish the config file (if needed):

    php artisan vendor:publish --provider="Barryvdh\HttpCache\ServiceProvider"
    
  2. First Use Case: Cache a route response for 10 minutes:

    Route::get('/cached-page', function () {
        return response()->view('cached-view');
    })->middleware('http_cache');
    
  3. Key Config: Check .env for:

    HTTP_CACHE_DRIVER=file  # or 'redis', 'memcached', etc.
    HTTP_CACHE_DEFAULT_TTL=3600  # Default TTL in seconds
    
  4. Verify: Access the cached route and inspect headers:

    Cache-Control: public, max-age=600
    X-Cache: HIT
    

Implementation Patterns

Core Workflows

  1. Route-Level Caching:

    Route::get('/products', ProductController::class)
         ->middleware('http_cache:public, max-age=3600'); // Custom headers
    
  2. Controller-Level Caching:

    public function index()
    {
        return Cache::remember('products_list', now()->addMinutes(10), function () {
            return Product::all();
        });
    }
    

    Combine with middleware for HTTP-level caching.

  3. Dynamic TTL:

    Route::get('/user/{id}', function ($id) {
        return response()->json(User::find($id));
    })->middleware('http_cache:public, max-age=' . config('http_cache.user_ttl'));
    
  4. Conditional Caching:

    Route::get('/dashboard', function () {
        if (auth()->check()) {
            return response()->view('dashboard');
        }
        return response()->view('guest-dashboard');
    })->middleware('http_cache:private, must-revalidate');
    

Integration Tips

  • With API Responses:

    Route::get('/api/data', function () {
        return response()->json(['data' => 'cached']);
    })->middleware('http_cache:public, s-maxage=86400, must-revalidate');
    
  • Cache Invalidation:

    // Invalidate a specific route
    Cache::forget('http_cache:GET:/products');
    
    // Invalidate all cached routes
    Cache::flush();
    
  • Custom Cache Store: Extend the Barryvdh\HttpCache\CacheStore class to integrate with custom storage backends.

  • Middleware Chaining:

    Route::get('/secure-cached', function () {
        return response()->view('secure-page');
    })->middleware(['auth', 'http_cache:private, max-age=300']);
    

Gotchas and Tips

Common Pitfalls

  1. Cache Headers Conflict:

    • If Cache-Control headers are set manually in the response, they override the middleware.
    • Fix: Use response()->header() after the middleware or adjust middleware priority.
  2. TTL Misconfiguration:

    • Default TTL (http_cache.options.default_ttl) may not apply if headers are explicitly set.
    • Fix: Ensure config matches your expectations:
      'default_ttl' => 3600, // 1 hour in seconds
      
  3. Private Cache Issues:

    • Private cache (Cache-Control: private) may not work as expected with shared proxies.
    • Fix: Use must-revalidate or no-store for sensitive data.
  4. Cache Store Quirks:

    • File-based cache (file driver) may cause race conditions in high-traffic apps.
    • Fix: Use redis or memcached for production.
  5. Middleware Order:

    • Place http_cache after authentication middleware to avoid caching unauthorized responses.
    • Fix: Adjust middleware groups in app/Http/Kernel.php:
      'web' => [
          \App\Http\Middleware\Authenticate::class,
          \Barryvdh\HttpCache\Middleware\HttpCache::class,
      ],
      

Debugging Tips

  1. Check Cache Status: Inspect headers for X-Cache:

    X-Cache: MISS  # Not cached
    X-Cache: HIT   # Cached
    
  2. Log Cache Events: Enable debug mode in config:

    'debug' => env('HTTP_CACHE_DEBUG', false),
    
  3. Clear Cache Manually:

    php artisan cache:clear
    php artisan http-cache:clear
    
  4. Test Locally: Use max-age=10 for quick testing:

    ->middleware('http_cache:public, max-age=10')
    

Extension Points

  1. Custom Cache Key: Override the cache key logic in a service provider:

    HttpCache::extend(function ($request) {
        return 'custom_key_' . $request->path();
    });
    
  2. Event Listeners: Listen for cache hits/misses:

    HttpCache::listen(function ($event) {
        Log::info('Cache event: ' . $event->type, $event->data);
    });
    
  3. Vary Headers: Support custom Vary headers for dynamic content:

    ->middleware('http_cache:public, max-age=3600, vary=Accept-Language')
    
  4. Conditional Logic: Skip caching for specific routes:

    if (request()->has('nocache')) {
        return response()->view('dynamic-page');
    }
    
    Route::get('/dynamic', function () {
        return response()->view('dynamic-page');
    })->middleware('http_cache:skip_if=nocache');
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor