Installation:
composer require suitmedia/laravel-cloudflare
Add Service Provider (Laravel 8.x):
In config/app.php, add:
Suitmedia\LaravelCloudflare\LaravelCloudflareServiceProvider::class,
Publish Config (optional but recommended):
php artisan vendor:publish --provider="Suitmedia\LaravelCloudflare\LaravelCloudflareServiceProvider" --tag="config"
This generates config/cloudflare.php.
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'),
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());
});
}
}
Model-Based Purging:
Use the saved() event to purge cache when models update:
static::saved(function ($model) {
Cloudflare::purge($model->getRouteKey());
});
save(), update(), and create().slug instead of id).Manual Purging: Trigger purges manually in controllers or commands:
Cloudflare::purge('/path/to/resource');
Cloudflare::purge(['/path1', '/path2']); // Array of paths
Queue-Based Purging (for async operations): Use Laravel queues to avoid blocking requests:
static::saved(function ($model) {
Cloudflare::purge($model->getRouteKey())->onQueue('cloudflare');
});
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
}
API Token Permissions: Ensure your Cloudflare API token has Zone:DNS and Cache Purge permissions. Use the Cloudflare API Token Generator to create one.
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).
Rate Limits: Cloudflare’s API has rate limits. Avoid rapid purges in loops or tests. Use queues for production workloads.
Wildcard Purges:
Purging / or * may trigger unnecessary cache invalidations. Prefer specific paths (e.g., /posts/1).
Laravel Caching Layers: If using Redis/Memcached, ensure Cloudflare purges align with your local cache strategy to avoid stale data.
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.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);
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');
});
}
}
Batch Processing: For bulk operations (e.g., imports), use chunking:
Post::chunk(100, function ($posts) {
$paths = $posts->pluck('getRouteKey')->toArray();
Cloudflare::purge($paths);
});
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('/');
}
});
How can I help you explore Laravel packages today?