A powerful and intuitive Laravel package for managing Cloudflare cache purging directly from your Laravel application. Streamline your cache management workflow with comprehensive commands, validation, and seamless integration.
- PHP 8.3+
- Laravel 10.x, 11.x, or 12.x
- Cloudflare account with API access
Install the package via Composer:
composer require fuelviews/laravel-cloudflare-cache
Run the install command for guided setup:
php artisan cloudflare-cache:install
This will:
- Publish the configuration file
- Guide you through credential setup
- Validate your configuration
- Provide helpful next steps
Alternatively, you can manually publish the configuration:
# Publish configuration
php artisan vendor:publish --tag="cloudflare-cache-config"
# Publish service provider for advanced customization (optional)
php artisan vendor:publish --tag="cloudflare-cache-provider"
Add your Cloudflare credentials to your .env
file:
# Required
CLOUDFLARE_CACHE_API_KEY=your_api_key_here
CLOUDFLARE_CACHE_ZONE_ID=your_zone_id_here
# Optional
CLOUDFLARE_CACHE_DEBUG=false
-
API Key: Create an API token at Cloudflare API Tokens
- Use the "Custom token" option
- Required permissions:
Zone:Zone:Read
,Zone:Cache Purge:Edit
- Zone Resources: Include specific zones or all zones
-
Zone ID: Find your Zone ID in your Cloudflare dashboard
- Go to your domain overview
- Find "Zone ID" in the right sidebar
- It's a 32-character hexadecimal string
The published configuration file config/cloudflare-cache.php
:
<?php
return [
/**
* Generate zone or global api key.
*
* @see https://dash.cloudflare.com/profile/api-tokens
*/
'api_key' => env('CLOUDFLARE_CACHE_API_KEY'),
/**
* The zone_id of your site on cloudflare dashboard.
*/
'identifier' => env('CLOUDFLARE_CACHE_ZONE_ID'),
/**
* Debug mode.
*/
'debug' => env('CLOUDFLARE_CACHE_DEBUG', false),
];
use Fuelviews\CloudflareCache\Facades\CloudflareCache;
// Purge everything from Cloudflare cache
$result = CloudflareCache::purgeEverything();
if ($result !== false) {
// Cache purged successfully
// $result contains the purge operation ID
echo "Cache purged successfully. Operation ID: {$result}";
} else {
// Purge failed
echo "Failed to purge cache";
}
use Fuelviews\CloudflareCache\CloudflareCacheInterface;
class CacheController extends Controller
{
public function clearCache(CloudflareCacheInterface $cloudflareCache)
{
try {
$result = $cloudflareCache->purgeEverything();
if ($result !== false) {
return response()->json([
'message' => 'Cache purged successfully',
'operation_id' => $result
]);
}
return response()->json(['message' => 'Failed to purge cache'], 500);
} catch (\Fuelviews\CloudflareCache\Exceptions\CloudflareCacheRequestException $e) {
return response()->json([
'message' => 'Cache purge failed',
'error' => $e->getMessage()
], 500);
}
}
}
The package includes smart environment detection:
use Fuelviews\CloudflareCache\Facades\CloudflareCache;
// Check if cache purging should be performed
if (CloudflareCache::ive()) {
$result = CloudflareCache::purgeEverything();
}
The ive()
method returns true
when:
- Running unit tests
- Debug mode is enabled (
CLOUDFLARE_CACHE_DEBUG=true
) - Application is in production environment and credentials are configured
Purge all Cloudflare cache:
php artisan cloudflare-cache:clear
Success Output:
Cloudflare cache successfully purged.
Error Output:
Error purging Cloudflare cache: Invalid API Token
Check your configuration for issues:
php artisan cloudflare-cache:validate
Successful validation:
Validating Cloudflare Cache configuration...
β
All configuration checks passed!
With errors:
Validating Cloudflare Cache configuration...
β Configuration Errors:
β’ API Key is required. Set CLOUDFLARE_CACHE_API_KEY in your .env file.
β’ Zone ID format appears invalid. Should be a 32-character hexadecimal string.
β οΈ Configuration Warnings:
β’ Debug mode is enabled in production environment. Consider disabling it.
β Configuration validation failed. Please fix the errors above.
Test your API connection and configuration:
php artisan cloudflare-cache:status
Successful status check:
Checking Cloudflare Cache configuration and API connection...
β
Configuration found:
API Key: ************************abc12345
Zone ID: 1234567890abcdef1234567890abcdef
Debug Mode: disabled
π Testing API connection...
β
API connection successful
π‘ Ready to purge Cloudflare cache
With configuration issues:
Checking Cloudflare Cache configuration and API connection...
β API Key not configured. Set CLOUDFLARE_CACHE_API_KEY in your .env file.
Clear cache automatically when content changes:
use Illuminate\Support\Facades\Event;
use Fuelviews\CloudflareCache\Facades\CloudflareCache;
// In your EventServiceProvider or wherever you register listeners
Event::listen('content.updated', function () {
if (CloudflareCache::ive()) {
CloudflareCache::purgeEverything();
}
});
For better performance, queue cache purging operations:
use Illuminate\Bus\Queueable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Fuelviews\CloudflareCache\Facades\CloudflareCache;
class PurgeCloudflareCache implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable;
public function handle()
{
try {
$result = CloudflareCache::purgeEverything();
if ($result !== false) {
logger()->info("Cloudflare cache purged successfully", [
'operation_id' => $result
]);
} else {
$this->fail('Failed to purge Cloudflare cache');
}
} catch (\Exception $e) {
logger()->error('Cloudflare cache purge failed', [
'error' => $e->getMessage()
]);
$this->fail($e);
}
}
}
// Dispatch the job
PurgeCloudflareCache::dispatch();
Publish and customize the service provider:
php artisan vendor:publish --tag="cloudflare-cache-provider"
This publishes CloudflareCacheServiceProvider
to your app/Providers
directory for customization.
Create middleware to automatically purge cache:
use Closure;
use Illuminate\Http\Request;
use Fuelviews\CloudflareCache\Facades\CloudflareCache;
class PurgeCloudflareMiddleware
{
public function handle(Request $request, Closure $next)
{
$response = $next($request);
// Purge cache on successful POST/PUT/DELETE requests
if ($request->isMethod(['post', 'put', 'delete']) && $response->isSuccessful()) {
if (CloudflareCache::ive()) {
CloudflareCache::purgeEverything();
}
}
return $response;
}
}
The package provides comprehensive error handling:
use Fuelviews\CloudflareCache\Facades\CloudflareCache;
use Fuelviews\CloudflareCache\Exceptions\CloudflareCacheRequestException;
try {
$result = CloudflareCache::purgeEverything();
if ($result !== false) {
// Success - $result contains operation ID
logger()->info('Cache purged', ['operation_id' => $result]);
} else {
// API returned success: false
logger()->warning('Cache purge returned false');
}
} catch (CloudflareCacheRequestException $e) {
// Handle Cloudflare API errors
logger()->error('Cloudflare cache purge failed', [
'message' => $e->getMessage(),
'status_code' => $e->getCode(),
]);
// Exception message format: "Request error: [API Error Message] | Code: [Error Code]"
// You can parse this for specific error handling
}
# Run all tests
composer test
# Run tests with coverage
composer test-coverage
# Code style formatting
composer format
The package automatically handles testing environments:
use Fuelviews\CloudflareCache\Facades\CloudflareCache;
class CloudflareCacheTest extends TestCase
{
public function test_cache_purging_works_in_tests()
{
// This returns true in testing environment
$this->assertTrue(CloudflareCache::ive());
// This succeeds without making actual API calls
$result = CloudflareCache::purgeEverything();
$this->assertTrue($result);
}
public function test_cache_purging_integration()
{
// Mock the facade for specific behavior
CloudflareCache::shouldReceive('purgeEverything')
->once()
->andReturn('operation-id-12345');
$response = $this->post('/admin/clear-cache');
$response->assertStatus(200)
->assertJson(['operation_id' => 'operation-id-12345']);
}
}
public function test_cache_clearing_endpoint()
{
// Test your cache clearing endpoint
$response = $this->actingAs($admin)
->post('/admin/cache/clear');
$response->assertStatus(200)
->assertJson(['message' => 'Cache purged successfully']);
}
β "API Key not configured"
- Ensure
CLOUDFLARE_CACHE_API_KEY
is set in your.env
file - Run
php artisan config:clear
after updating environment variables - Verify the API key has proper permissions
β "Zone ID format appears invalid"
- Zone IDs should be exactly 32 characters (hexadecimal)
- Check your Cloudflare dashboard for the correct Zone ID
- Ensure no extra spaces or characters
β "Request error: Invalid API Token"
- Verify your API token has the required permissions:
Zone:Zone:Read
Zone:Cache Purge:Edit
- Check that the token hasn't expired
- Ensure the token is active in your Cloudflare dashboard
β "Request error: Zone not found"
- Verify the Zone ID matches your domain
- Ensure the API token has access to the specified zone
- Check that the zone is active in Cloudflare
Enable debug mode for detailed information:
CLOUDFLARE_CACHE_DEBUG=true
With debug mode enabled:
- Cache purging works in all environments
- Additional logging information is available
- The
ive()
method always returnstrue
Use built-in validation to diagnose issues:
# Comprehensive configuration check
php artisan cloudflare-cache:validate
# API connection test
php artisan cloudflare-cache:status
Check Laravel logs for detailed error information:
# View recent logs
tail -f storage/logs/laravel.log
# Search for Cloudflare-related logs
grep -i "cloudflare" storage/logs/laravel.log
Purges all cache from Cloudflare for the configured zone.
Returns:
string
: Operation ID on successfalse
: On failure (when API returns success: false)
Throws:
CloudflareCacheRequestException
: When API request fails
Determines if cache purging should be performed based on environment and configuration.
Returns:
true
: When cache purging should be performedfalse
: When cache purging should be skipped
Command | Description |
---|---|
cloudflare-cache:install |
Guided installation process |
cloudflare-cache:clear |
Purge all Cloudflare cache |
cloudflare-cache:validate |
Validate configuration settings |
cloudflare-cache:status |
Check API connection and configuration |
We welcome contributions! Please see CONTRIBUTING.md for details.
git clone https://github.com/fuelviews/laravel-cloudflare-cache.git
cd laravel-cloudflare-cache
composer install
composer test
Please see CHANGELOG for more information on what has changed recently.
Please review our security policy on how to report security vulnerabilities.
The MIT License (MIT). Please see License File for more information.
Built with β€οΈ by the Fuelviews team