composer require leknoppix/laravel-cloudflare
Leknoppix\LaravelCloudflare\LaravelCloudflareServiceProvider::class to config/app.php under providers.php artisan vendor:publish --provider="Leknoppix\LaravelCloudflare\LaravelCloudflareServiceProvider" --tag="config"
.env:
CLOUDFLARE_API_TOKEN=your_api_token_here
CLOUDFLARE_ZONE_ID=your_zone_id_here
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.
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];
}
Manual Purging:
Use the PurgeCloudflareCache facade or service container:
use Leknoppix\LaravelCloudflare\Facades\PurgeCloudflareCache;
PurgeCloudflareCache::purge(['/path/to/purge']);
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());
});
}
Queue Purging for Performance: Dispatch a job to avoid blocking the request:
use Leknoppix\LaravelCloudflare\Jobs\PurgeCloudflareCacheJob;
PurgeCloudflareCacheJob::dispatch(['/path/to/purge'])->onQueue('cloudflare');
protected $purgeCachePaths = ['/products/{id}', '/categories/{category_id}'];
public function getPurgeCachePaths()
{
return [
'/products/' . $this->id,
'/categories/' . $this->category->id,
];
}
public function shouldPurgeCache()
{
return $this->published_at !== null;
}
PurgeCloudflareCache::purge(['/path1', '/path2', '/path3']);
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.
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.
Rate Limits: Cloudflare imposes purge rate limits. Exceeding limits may cause delays or failures. Tip: Implement retries or queue delays for bulk operations.
Path Wildcards:
Overusing wildcards (e.g., /*) can purge unintended cache. Prefer specific paths like /posts/{id}.
Tip: Test purge paths in Cloudflare Dashboard first.
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.
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"]}'
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');
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
}
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]));
});
Performance: For high-traffic sites, consider:
/robots.txt).How can I help you explore Laravel packages today?