lat4732's avatar
Level 12

How to clear CDN cache while uploading with Laravel Storage

Hello everyone!

I noticed that whenever i override an image with the same name but obviously different image content, the CDN has already cached the old one and keep showing the old one. Is there any way to somehow clear the CDN cache or maybe set something like Cache-Control header while uploading? Here's how I upload

public function saveLogoChanges(Request $request) {
    $request->validate([
        'formNormal' => 'mimes:jpg,jpeg,png,webp',
        'formSticky' => 'mimes:jpg,jpeg,png,webp',
    ]);

    if($request->hasFile('formNormal')) {

        $image = Image::make($request->formNormal)->resize(140, 35)->encode($request->file('formNormal')->extension(), 90);

        // Delete Possible Logo Files
        \Storage::disk('cdnplus_images')->delete('assets/img/logo.svg');
        \Storage::disk('cdnplus_images')->delete('assets/img/logo.webp');
        \Storage::disk('cdnplus_images')->delete('assets/img/logo.png');
        \Storage::disk('cdnplus_images')->delete('assets/img/logo.jpg');
        // Delete Possible Logo Files

        if(\Storage::disk('cdnplus_images')->put("assets/img/logo." . $request->file('formNormal')->extension(), (string) $image, 'public')) {
            GeneralSettingsModel::where('id', 1)->update([
                'logo_path_fixed' => 'logo.' . $request->file('formNormal')->extension()
            ]);
        }
    }
    if($request->hasFile('formSticky')) {

        $image = Image::make($request->formSticky)->resize(140, 35)->encode($request->file('formSticky')->extension(), 90);

        // Delete Possible Logo Files
        \Storage::disk('cdnplus_images')->delete('assets/img/logo_sticky.svg');
        \Storage::disk('cdnplus_images')->delete('assets/img/logo_sticky.webp');
        \Storage::disk('cdnplus_images')->delete('assets/img/logo_sticky.png');
        \Storage::disk('cdnplus_images')->delete('assets/img/logo_sticky.jpg');
        // Delete Possible Logo Files

        if(\Storage::disk('cdnplus_images')->put("assets/img/logo_sticky." . $request->file('formSticky')->extension(), (string) $image, 'public')) {
            GeneralSettingsModel::where('id', 1)->update([
                'logo_path_sticky' => 'logo_sticky.' . $request->file('formSticky')->extension()
            ]);
        }
    }
    return back()->with('success', 'Successfully updated website\'s logo');
}

I tried a simple solution to add ?time={{ time() }} where I display the logos, but this causes slower page load obviously. Any ideas, guys?

0 likes
2 replies

Please or to participate in this conversation.