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

leknoppix/laravel-cloudflare

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:
    composer require leknoppix/laravel-cloudflare
    
  2. Register Service Provider: Add Leknoppix\LaravelCloudflare\LaravelCloudflareServiceProvider::class to config/app.php under providers.
  3. Publish Config (if needed):
    php artisan vendor:publish --provider="Leknoppix\LaravelCloudflare\LaravelCloudflareServiceProvider" --tag="config"
    
  4. Configure Cloudflare API Token: Set your Cloudflare API token and zone ID in .env:
    CLOUDFLARE_API_TOKEN=your_api_token_here
    CLOUDFLARE_ZONE_ID=your_zone_id_here
    

First Use Case

Purge Cloudflare cache when a model updates. For example, in your User model:

use Leknoppix\LaravelCloudflare\Traits\PurgesCloudflareCache;

class User extends Model
{
    use PurgesCloudflareCache;

    protected $purgeCachePaths = ['/users/*'];
}

Now, every time a User model is updated, Cloudflare cache for /users/* will be purged.


Implementation Patterns

Common Workflows

  1. Model-Based Purging: Use the PurgesCloudflareCache trait on Eloquent models to auto-purge cache on updates.

    class Post extends Model
    {
        use PurgesCloudflareCache;
    
        protected $purgeCachePaths = ['/posts/{id}'];
    }
    

    Override getPurgeCachePaths() to dynamically generate paths:

    public function getPurgeCachePaths()
    {
        return ['/posts/' . $this->id];
    }
    
  2. Manual Purging: Use the PurgeCloudflareCache facade or service container:

    use Leknoppix\LaravelCloudflare\Facades\PurgeCloudflareCache;
    
    PurgeCloudflareCache::purge(['/path/to/purge']);
    
  3. Event-Based Purging: Listen to model events (e.g., saved) and trigger purges:

    public static function bootPurgeCache()
    {
        static::saved(function ($model) {
            PurgeCloudflareCache::purge($model->getPurgeCachePaths());
        });
    }
    
  4. Queue Purging for Performance: Dispatch a job to avoid blocking the request:

    use Leknoppix\LaravelCloudflare\Jobs\PurgeCloudflareCacheJob;
    
    PurgeCloudflareCacheJob::dispatch(['/path/to/purge'])->onQueue('cloudflare');
    

Integration Tips

  • Dynamic Paths: Use model attributes or relationships to construct purge paths:
    protected $purgeCachePaths = ['/products/{id}', '/categories/{category_id}'];
    
    public function getPurgeCachePaths()
    {
        return [
            '/products/' . $this->id,
            '/categories/' . $this->category->id,
        ];
    }
    
  • Conditional Purging: Skip purging for drafts or unpublished content:
    public function shouldPurgeCache()
    {
        return $this->published_at !== null;
    }
    
  • Bulk Purging: Purge multiple paths at once:
    PurgeCloudflareCache::purge(['/path1', '/path2', '/path3']);
    

Gotchas and Tips

Pitfalls

  1. API Token Permissions: Ensure your Cloudflare API token has Zone:Purge permissions. A token with insufficient permissions will fail silently or throw errors. Debug: Check Cloudflare API response for 403 Forbidden errors.

  2. Zone ID Mismatch: Using the wrong CLOUDFLARE_ZONE_ID will result in purges failing for all paths. Debug: Verify the zone ID matches the domain in your Laravel app.

  3. Rate Limits: Cloudflare imposes purge rate limits. Exceeding limits may cause delays or failures. Tip: Implement retries or queue delays for bulk operations.

  4. Path Wildcards: Overusing wildcards (e.g., /*) can purge unintended cache. Prefer specific paths like /posts/{id}. Tip: Test purge paths in Cloudflare Dashboard first.

  5. Environment-Specific Config: Ensure .env values are correct for all environments (e.g., staging vs. production). Use config('cloudflare.zone_id') in code to avoid hardcoding.

Debugging

  • Enable Logging: Add to config/cloudflare.php:

    'log_responses' => env('CLOUDFLARE_LOG_RESPONSES', false),
    

    Check Laravel logs for API response details.

  • Manual API Testing: Test purge endpoints directly via Cloudflare API:

    curl -X DELETE "https://api.cloudflare.com/client/v4/zones/YOUR_ZONE_ID/purge_cache" \
         -H "Authorization: Bearer YOUR_API_TOKEN" \
         -H "Content-Type: application/json" \
         --data '{"files":["/path/to/purge"]}'
    

Tips

  1. Cache Versioning: Append a version query string to assets to bypass Cloudflare cache during development:

2. **Partial Purges**:
 Use Cloudflare’s [partial cache purging](https://developers.cloudflare.com/api/operations/cache-purge-purge-cache-by-file-path) for granular control:
 ```php
 PurgeCloudflareCache::purge(['/posts/123'], 'partial');
  1. Fallback for Offline: Gracefully handle Cloudflare API failures:

    try {
        PurgeCloudflareCache::purge($paths);
    } catch (\Exception $e) {
        Log::warning("Cloudflare purge failed: " . $e->getMessage());
        // Fallback: Log error or notify admin
    }
    
  2. Testing: Mock the Cloudflare API in tests using Laravel’s HTTP client:

    $this->mock(Http::class, function ($mock) {
        $mock->shouldReceive('delete')
             ->with('https://api.cloudflare.com/...')
             ->andReturn(Http::response(['success' => true]));
    });
    
  3. Performance: For high-traffic sites, consider:

    • Batching: Purge multiple paths in a single API call.
    • Caching: Cache purge responses if paths are static (e.g., /robots.txt).
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.
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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