How To Delete Old File While Uploading New

How to delete older file/image when you update the post?

To make the folder clean and remove all unused file/image from the folder, delete old files.

A Step-by-Step Guide to Updating Posts and Cleaning Up Images in Laravel

Learn How to Update Your Posts and Delete Unused Images in Laravel.

As your website grows and you create more and more blog posts, you might face some challenges in managing your content and images.

For example, you might want to update your old posts with new information or images, but you don’t want to leave behind the old images that are no longer relevant or used. These unused images can take up valuable space in your server and affect your website performance and loading speed.

Solution: Laravel provides us with a great solution to keep our blog folder clean and gives us the control to manage all the unnecessary files. When we update our old posts, we can check and delete the old files if we upload new ones.

So, we will create a function where we will check if the post has an image already. Then the next actions will depend on it.

  • Check if the post has an image
  • If yes, then delete and upload a new one (if the user wants)
  • If no, then upload a new image (if the user wants)
  • The field could be left empty as per the user’s requirement

Check if the file exists

Let’s see the code to check if there is already a file available in the folder.

        if ($request->hasFile('image')) {
            $oldfile = public_path('images/post_img/') . $post->image;
            $filename = 'image' . '_' .time() . '.' . $request->file('image')->getClientOriginalExtension();
            if(File::exists($oldfile)){
                File::delete($oldfile);
            }

We store the file path and the file name in a variable called $oldfile. This will make it easy to use the long file path if we need it for heavy actions.

Basically what the above code means: We check if the user is uploading a file. If yes, then we name it and then check if there is already a file exists. Here again, if the condition is yes, we will delete it and then update it with $post->update();

  • If the request has a file, change its name, and store it in a variable called $filename
  • If there is already a file (old file), remove it if(File::exists($oldfile)){File::delete($olderfile);}

Function for deleting old image and updating with new image

use File;

public function update(Request $request, Post $post)
    {
        $validatedData = $this->validate($request, [
            'title' => 'required',
            'category_id' => 'required',
            'description' => 'required',
            'image' => 'sometimes|mimes:jpeg,jpg,gif,png'
        ]);

        if ($request->hasFile('image')) {
            $oldfile = public_path('images/post_img/') . $post->image;
            $filename = 'image' . '_' .time() . '.' . $request->file('image')->getClientOriginalExtension();
            if(File::exists($oldfile)){
                File::delete($oldfile);
            }

            $request->file('image')->storeAs('post_img', $filename, 'public');

            $validatedData['image'] = $filename;
        }


    
        $post->update($validatedData);

        return redirect()->back()->withMessage('Your updated post is ready now!');
    }

Related Posts