I am trying to delete multiple images using product_id, I am able to delete one image at a time but am figuring out how i can insert a variable like $i=0 to a loop over but it does not work in laravel. so far this is my code
public function ImageDelete($slider_id) { //int $i=0; Had introduced this but doesn't work $slider = Products::findOrFail($slider_id); foreach($slider as $product){ $product_images=$slider->images()->get(); $image_path = public_path().'images2\'.$product_images[0]->filename; File::delete($image_path); //$i++; } $slider->delete(); return response()->json(['success'=>'Pics deleted successfully!']); }
Advertisement
Answer
The findOrFail
method return only one item. So you cannot iterate over it.
You can use the each
method
$product = Products::findOrFail($id); $images = $product->images()->get(); $images->each(function ($file, $key) { $filePath = public_path("images2/") . $file->filename; File::delete($filePath); }); // Delete the product $product->delete();