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

suitmedia/laravel-cloudflare

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require suitmedia/laravel-cloudflare
    
  2. Add Service Provider (Laravel 8.x): In config/app.php, add:

    Suitmedia\LaravelCloudflare\LaravelCloudflareServiceProvider::class,
    
  3. Publish Config (optional but recommended):

    php artisan vendor:publish --provider="Suitmedia\LaravelCloudflare\LaravelCloudflareServiceProvider" --tag="config"
    

    This generates config/cloudflare.php.

  4. Configure API Token: Edit config/cloudflare.php with your Cloudflare API token and zone ID:

    'token' => env('CLOUDFLARE_API_TOKEN'),
    'zone_id' => env('CLOUDFLARE_ZONE_ID'),
    

First Use Case

Purge Cloudflare cache when a model updates:

use Suitmedia\LaravelCloudflare\Facades\Cloudflare;

class Post extends Model
{
    protected static function booted()
    {
        static::saved(function ($model) {
            Cloudflare::purge($model->getRouteKey());
        });
    }
}

Implementation Patterns

Core Workflows

  1. Model-Based Purging: Use the saved() event to purge cache when models update:

    static::saved(function ($model) {
        Cloudflare::purge($model->getRouteKey());
    });
    
    • Works with save(), update(), and create().
    • Supports custom route keys (e.g., slug instead of id).
  2. Manual Purging: Trigger purges manually in controllers or commands:

    Cloudflare::purge('/path/to/resource');
    Cloudflare::purge(['/path1', '/path2']); // Array of paths
    
  3. Queue-Based Purging (for async operations): Use Laravel queues to avoid blocking requests:

    static::saved(function ($model) {
        Cloudflare::purge($model->getRouteKey())->onQueue('cloudflare');
    });
    

Integration Tips

  • Route Caching: Combine with Laravel's route caching (php artisan route:cache) for optimal performance.

    Cloudflare::purge('/'); // Purge all routes after route caching
    
  • Event-Based Purging: Listen to custom events (e.g., PostPublished) for granular control:

    event(new PostPublished($post));
    // In EventServiceProvider:
    PostPublished::listen(function ($event) {
        Cloudflare::purge($event->post->getRouteKey());
    });
    
  • Environment-Specific Config: Use .env for environment-specific tokens/zone IDs:

    CLOUDFLARE_API_TOKEN=your_token_here
    CLOUDFLARE_ZONE_ID=your_zone_id_here
    
  • Fallback Logic: Handle API failures gracefully:

    try {
        Cloudflare::purge('/path');
    } catch (\Exception $e) {
        Log::error("Cloudflare purge failed: " . $e->getMessage());
        // Fallback: Local cache or manual retry
    }
    

Gotchas and Tips

Pitfalls

  1. API Token Permissions: Ensure your Cloudflare API token has Zone:DNS and Cache Purge permissions. Use the Cloudflare API Token Generator to create one.

  2. Zone ID Mismatch: Verify the zone_id in config/cloudflare.php matches the exact ID from Cloudflare’s dashboard (e.g., 123e4567-e89b-12d3-a456-426614174000).

  3. Rate Limits: Cloudflare’s API has rate limits. Avoid rapid purges in loops or tests. Use queues for production workloads.

  4. Wildcard Purges: Purging / or * may trigger unnecessary cache invalidations. Prefer specific paths (e.g., /posts/1).

  5. Laravel Caching Layers: If using Redis/Memcached, ensure Cloudflare purges align with your local cache strategy to avoid stale data.

Debugging

  • Enable Logging: Add this to config/cloudflare.php to log API calls:

    'debug' => env('APP_DEBUG', false),
    

    Check logs in storage/logs/laravel.log.

  • Test API Connectivity: Use Tinker to verify the connection:

    php artisan tinker
    >>> \Suitmedia\LaravelCloudflare\Facades\Cloudflare::purge('/test');
    

    If it fails, check the token/zone ID or network proxies.

  • Common Errors:

    • 403 Forbidden: Invalid token or insufficient permissions.
    • 404 Not Found: Incorrect zone ID or path.
    • 429 Too Many Requests: Hit rate limits; implement retries or queues.

Extension Points

  1. Custom Purge Logic: Extend the Purge class to add logic (e.g., path transformation):

    namespace App\Services;
    use Suitmedia\LaravelCloudflare\Purge;
    
    class CustomPurge extends Purge
    {
        public function getPath($model)
        {
            return '/custom/' . parent::getPath($model);
        }
    }
    

    Bind it in AppServiceProvider:

    $this->app->bind(\Suitmedia\LaravelCloudflare\Contracts\Purge::class, App\Services\CustomPurge::class);
    
  2. Queueable Purges: Implement ShouldQueue for async operations:

    use Illuminate\Bus\Queueable;
    
    class Post extends Model
    {
        use Queueable;
    
        protected static function booted()
        {
            static::saved(function ($model) {
                Cloudflare::purge($model->getRouteKey())->onQueue('cloudflare');
            });
        }
    }
    
  3. Batch Processing: For bulk operations (e.g., imports), use chunking:

    Post::chunk(100, function ($posts) {
        $paths = $posts->pluck('getRouteKey')->toArray();
        Cloudflare::purge($paths);
    });
    
  4. Webhook Integration: Trigger purges via Cloudflare webhooks (e.g., on DNS changes):

    Route::post('/cloudflare-webhook', function (Request $request) {
        if ($request->input('event') === 'dns_record_purge') {
            Cloudflare::purge('/');
        }
    });
    
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope