I use Cloudflare to cache pages for a day. Recently I built the Arbeitnow blog using Statamic. When I update the content, I want the cache to be updated and the latest changes to be shown to the visitor.
When I deploy changes to content, I added a new Laravel command as part of the deployment flow. Important thing to note is that the Purge by single-file (by URL) allows only 30 entries at a time.
With statamic, I just grab the URLs from the Entry
repository for a single collection. You could filter more, perhaps grab only records that have been updated in the last day, or since the last deployment.
This is what I have in the handle
method. For this, you need two things:
- Zone ID (it’s on your site page in Cloudflare portal)
- API Key (Generate one here with permissions for clearing / purging cache in a zone)
// use config() to grab it from your environment
$apiKey = '';
$zoneId = '';
$all = Entry::query()
->where('collection', 'collection_name')
->where('published', true)
->get();
foreach ($all->chunk(30) as $entries){
$files = [];
/** @var Entry $entry */
foreach ($entries as $entry){
$files[] = url($entry->uri);
}
$urls = [
'files' => $files
];
$http = Http::withBody(json_encode($urls),'application/json')
->withToken($apiKey)
->post('https://api.cloudflare.com/client/v4/zones/' . $zoneId . '/purge_cache');
$this->info('Submitted to Cloudflare with status: ' . $http->status());
if (!$http->ok()){
dump($http->body());
}
}