DEV Community

webfuelcode
webfuelcode

Posted on

How To Delete Old Image While Updating The Post

The Laravel project can go and run well without touching the older files. For this, you will use the simple update function and update with the new text entered by the user.

The problem may occur when you grow and have thousands of images and files that are not in use.

The site will take time to load and at this time we know the power of fast-loading websites and how it impacts user performance.

Check if there is a file

If there is already a file we will remove it and update it with a new one. Or we can just leave to keep the older if the post has one.

        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);
            }
Enter fullscreen mode Exit fullscreen mode

Full update function

Complete the update function by validating the title, description, category id, and image field.

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!');
    }
Enter fullscreen mode Exit fullscreen mode

Post: How To Delete Old File While Uploading New

Top comments (0)