fuelviews / laravel-cloudflare-cache
Laravel cloudflare cache package
Installs: 1 312
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 1
Forks: 0
Open Issues: 0
Requires
- php: ^8.3
- guzzlehttp/guzzle: *
- illuminate/contracts: ^10.0||^11.0||^12.0
- spatie/laravel-package-tools: ^1.92
Requires (Dev)
- driftingly/rector-laravel: ^2.0
- laravel/pint: ^1.14
- nunomaduro/collision: ^8.1.1||^7.10.0
- orchestra/testbench: ^10.2||^9.0.0||^8.22.0
- pestphp/pest: ^3.0||^2.34
- pestphp/pest-plugin-arch: ^3.0||^2.7
- pestphp/pest-plugin-laravel: ^3.2||^2.3
- rector/rector: ^2.0
README
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.
๐ Requirements
- PHP 8.3+
- Laravel 10.x, 11.x, or 12.x
- Cloudflare account with API access
๐ Installation
Install the package via Composer:
composer require fuelviews/laravel-cloudflare-cache
Quick Setup
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
Manual Setup
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"
โ๏ธ Configuration
Environment Variables
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
Getting Your Cloudflare Credentials
-
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
Configuration File
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), ];
๐ฏ Basic Usage
Using the Facade
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"; }
Using Dependency Injection
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); } } }
Environment-Aware Functionality
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
๐ ๏ธ Artisan Commands
Cache Clear Command
Purge all Cloudflare cache:
php artisan cloudflare-cache:clear
Success Output:
Cloudflare cache successfully purged.
Error Output:
Error purging Cloudflare cache: Invalid API Token
Validate Configuration
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.
Check Status
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.
๐๏ธ Advanced Usage
Integration with Events
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(); } });
Using in Queue Jobs
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();
Custom Service Provider
Publish and customize the service provider:
php artisan vendor:publish --tag="cloudflare-cache-provider"
This publishes CloudflareCacheServiceProvider
to your app/Providers
directory for customization.
Middleware Integration
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; } }
๐ก๏ธ Exception Handling
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 }
๐งช Testing
Running Package Tests
# Run all tests composer test # Run tests with coverage composer test-coverage # Code style formatting composer format
Testing in Your Application
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']); } }
Feature Testing
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']); }
๐ Troubleshooting
Common Issues
โ "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
Debug Mode
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
Validation Commands
Use built-in validation to diagnose issues:
# Comprehensive configuration check php artisan cloudflare-cache:validate # API connection test php artisan cloudflare-cache:status
Logging
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
๐ API Reference
CloudflareCacheInterface
purgeEverything(): bool|string
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
ive(): bool
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
Available Commands
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 |
๐ค Contributing
We welcome contributions! Please see CONTRIBUTING.md for details.
Development Setup
git clone https://github.com/fuelviews/laravel-cloudflare-cache.git cd laravel-cloudflare-cache composer install composer test
๐ Changelog
Please see CHANGELOG for more information on what has changed recently.
๐ Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
๐จโ๐ป Credits
๐ License
The MIT License (MIT). Please see License File for more information.
Built with โค๏ธ by the Fuelviews team