Search code examples
phplaravelintervention

Delete images where image path is saved with path in database


I am uploading an image and while saving to the database I am adding path to the location along with the filename.

eg : product/name/L4I84qXltYvCCDsAeQzi7fzZfKF3WTRa1LPOPGxj.jpeg

Why adding location where I can call them through asset()? The table is also used by API application where it requires the url format like this.

My Controller Cdde

  //! Product Image
        if ($request->hasFile('product_image')) {
            $product_image = $request->file('product_image');
            $product_image_extension = $product_image->getClientOriginalExtension();
            $product_image_filename =  Str::slug($request->input('product_code')) .  '.' . Str::random(3) . "." . $product_image_extension;
            $product_image_location = public_path('assets/products/' . $product_image_filename);
            Image::make($product_image)->resize(300, 300)->save($product_image_location);
        }

Products::create([
//Other Fields 
            'image' => 'assets/products/' . $product_image_filename
        ]);

I am wondering how do I remove the image and add a new image

For comparison, I need the image file name. Since I am using the path, I am getting the path prefixed to the Image Name.


Solution

  • use Illuminate\Support\Facades\File 
    
    
    
    $image_path = "/images/filename.ext";  // Value is not URL but directory file path
        if(File::exists($image_path)) {
            File::delete($image_path);
        }