Laravel Cache Routes with Cloudflare
You can install the package via composer:
composer require yediyuz/laravel-cloudflare-cache
You can publish the config file with:
php artisan vendor:publish --tag="cloudflare-cache-config"
Add environment variables to .env file
[email protected] #Cloudflare account email address
CLOUDFLARE_CACHE_KEY=XXXXXXX #Cloudflare API_KEY
CLOUDFLARE_CACHE_IDENTIFIER=XXXXXXX #ZONE_ID
CLOUDFLARE_DEFAULT_CACHE_TTL=600 #10 minutes
CLOUDFLARE_CACHE_DEBUG=false
Additionally, you can use cache tags to easily invalidate cached content. Simply specify the expiration time in seconds using the ttl parameter. For instance:
Route::cache(tags: ['tag1', 'tag2'], ttl: 600)->group(function () {
Route::get('/tag', function () {
return 'content';
});
});
To purge the cache, the package provides methods such as purgeEverything(), purgeByUrls(), purgeByPrefixes(), purgeByTags(), and purgeByHosts(). You can use these according to your needs. For example:
CloudflareCache::purgeByUrls([
'https://example.com/hello',
]);
Finally, remember to update and purge the cache after modifying data. For instance, after updating a post, you can use purgeByUrls() to clear the cache for the corresponding URL:
CloudflareCache::purgeByUrls([
route('post.show', $post->id)
]);
This ensures that the latest data is served to your users.
You can learn more about this package, get full installation instructions, and view the source code on GitHub. https://github.com/yediyuz/laravel-cloudflare-cache