phpimageupdateslaravel-10laravel-11

How to check and delete existing profile image before updating with a new one?


Whenever a request is made to update a profile image, my script must check whether an existing image is present. If so, it should delete the existing image before creating a new one.

public function updateImage(Request $request)
{
    $profile = Admin::find(Auth::guard('admin')->id());

    $file_existsion = $request->image->getClientOriginalExtension();
    $file_name = time().'.'.$file_existsion;
    $path = 'images/tourism/header';
    $request->image->move($path, $file_name);

    if (file_exists($file_name) && $request->image == '') {
        $profile->auth()->guard('admin')->update(['image' => $file_name]);
    } elseif ($request->hasFile('image') && $request->image != null) {
        unlink(public_path().'images/tourism/header'.$profile->image);
        $profile->image = $file_name;
    }
    
    return redirect()->back();
}

Solution

  • You Check if the profile already has an image, delete it if exists

    if (!empty($profile->image) && file_exists(public_path($path . '/' . $profile->image))) {
            unlink(public_path($path . '/' . $profile->image));
        }