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

richan-fongdasen/laravel-varnishable

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require richan-fongdasen/laravel-varnishable
    

    Publish the config file:

    php artisan vendor:publish --provider="RichanFongdasen\Varnishable\VarnishableServiceProvider" --tag="config"
    
  2. Configure Varnish Edit config/varnishable.php:

    'host' => '127.0.0.1',
    'port' => 6081,
    'timeout' => 5.0,
    
  3. First Use Case: Cache a Route Add the Varnishable middleware to a route or group:

    Route::get('/cached-page', function () {
        return response()->json(['data' => 'Cached via Varnish']);
    })->middleware('varnishable');
    

Where to Look First

  • Middleware: app/Http/Middleware/Varnishable.php (default behavior).
  • Config: config/varnishable.php (adjust Varnish server settings).
  • Facade: Varnishable::purge() (for manual cache invalidation).

Implementation Patterns

1. Route-Level Caching

Use the varnishable middleware on routes that should be cached:

Route::get('/products/{id}', [ProductController::class, 'show'])
    ->middleware('varnishable');

2. Dynamic Cache Keys

Override the default cache key logic (e.g., for API responses):

use RichanFongdasen\Varnishable\Traits\Varnishable;

class ProductController extends Controller
{
    use Varnishable;

    public function show($id)
    {
        $response = response()->json(['product' => Product::find($id)]);
        return $this->varnishable($response, "product_{$id}");
    }
}

3. Manual Cache Invalidation

Purge Varnish cache programmatically (e.g., after updates):

use RichanFongdasen\Varnishable\Facades\Varnishable;

public function update(Product $product)
{
    $product->update($request->all());
    Varnishable::purge("product_{$product->id}");
}

4. Conditional Caching

Skip Varnish for non-GET requests or authenticated users:

Route::middleware(['varnishable', 'throttle:60'])->group(function () {
    Route::get('/public-data', [DataController::class, 'index']);
});

5. Integration with Laravel Echo/Pusher

Cache WebSocket events (if Varnish supports X-Push-Channel headers):

Route::get('/broadcasting/auth', function () {
    return response()->json(['data' => 'cached-auth']);
})->middleware('varnishable');

Gotchas and Tips

Pitfalls

  1. Varnish Server Mismatch

    • Ensure the host/port in config/varnishable.php match your Varnish instance.
    • Test connectivity with:
      telnet 127.0.0.1 6081
      
  2. Cache Key Collisions

    • Default keys use the full URL + query string. Override if needed:
      $this->varnishable($response, "custom_key_{$id}");
      
  3. Non-200 Responses

    • Varnish only caches 2xx/3xx responses. Handle errors gracefully:
      if ($response->isClientError()) {
          return $response; // Skip caching
      }
      
  4. TTL Conflicts

    • Varnish’s default TTL (e.g., s=3600) may override Laravel’s cache. Set explicit headers:
      $response->header('Cache-Control', 'public, max-age=300');
      
  5. HTTPS/SSL Issues

    • If Varnish is behind a load balancer, ensure X-Forwarded-Proto headers are trusted:
      TrustedProxy::setTrustedProxies(['127.0.0.1']);
      

Debugging Tips

  1. Check Varnish Logs

    tail -f /var/log/varnish/varnish.log
    
  2. Test Locally Use varnishd -n test -f /etc/varnish/default.vcl -s malloc,100M for isolated testing.

  3. Disable Caching Temporarily Set VARNISHABLE_ENABLED=false in .env to bypass middleware.

  4. Monitor Cache Hits/Misses Add Varnish stats to your dashboard:

    curl http://127.0.0.1:6082/?show=vary
    

Extension Points

  1. Custom Middleware Extend VarnishableMiddleware to add logic:

    class CustomVarnishable extends VarnishableMiddleware
    {
        protected function shouldCache(Request $request)
        {
            return parent::shouldCache($request) && !$request->has('nocache');
        }
    }
    
  2. VCL Snippets Inject custom Varnish Configuration Language (VCL) via config:

    'vcl_snippet' => '@@ include "custom.vcl";',
    
  3. Event Listeners Hook into varnishable.purged events:

    Varnishable::purge('key')->then(function () {
        Log::info('Varnish cache purged');
    });
    
  4. Queue Purging Offload purges to a queue for high-traffic sites:

    Queue::push(new PurgeVarnishJob('key'));
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui