Cristian Ilisei
Cristian Ilisei

Reputation: 45

How can I delete the image once the row in the table is deleted?

How can I delete the image once the row in the table is deleted ?

Product controller :

Store function

public function store(Request $request)
    {

        $product = new Product();

        $request->validate([
            'name' => 'required',
            'category_id' => 'required',
            'image' => 'required',
            'description' => 'required|min:1',
            'tag' => 'required'
        ]);

        if($request->hasFile('image')){
            $image = $request->file('image');
            $filename = $request->name;
            $foldername = $request->name;
            $imagename = $filename .'.' . $request->image->extension();
            $path = public_path('images/produse/'. $filename .'/');

            if(!File::exists($path)){
                File::makeDirectory($path, 0777, true, true);
            }

            Image::make($image)->resize(200, 200)->save( public_path('images/produse/' . $foldername .  '/' . $imagename ));
        }

        $product->name = $request->name;
        $product->category_id = $request->category_id;
        $product->description = $request->description;
        $product->tag = $request->tag;
        $product->image = "/$foldername/$imagename";
        $product->save();

        return redirect('/products')->with('success', 'Produs adaugat cu succes !');
    }

Delete function

public function destroy(Product $product)
    {
        $product->delete();

        return redirect('/products')->with('danger', 'Produs sters cu succes !');
    }

I want when I delete a product, to delete the folder with that image .. How can i do that ?

Upvotes: 0

Views: 102

Answers (2)

A.A Noman
A.A Noman

Reputation: 5270

You may use like this

use File;

Add above line in header section

public function destroy(Product $product)
{

    $originalPath  = getcwd()."/images/{$product-> image}";

    if(File::exists($originalPath)){
         File::delete($originalPath);
    }

    $product->delete();

    return redirect('/products')->with('danger', 'Produs sters cu succes !');
}

You follow this Document

Upvotes: 1

zlatan
zlatan

Reputation: 3951

If you're saving full path of an image to your product, you can check if file exists in public folder, and then delete it:

public function destroy(Product $product)
    {
        $image_path = public_path($product->image);
        if (File::exists($image_path)) {
           //File::delete($image_path) or;
           unlink($image_path);
        }
        $product->delete();

    return redirect('/products')->with('danger', 'Produs sters cu succes !');
}

Edit:

If you want to delete the whole folder, you can use:

File::deleteDirectory(public_path('path/to/your/folder'));

Upvotes: 1

Related Questions