Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
562 views
in Technique[技术] by (71.8m points)

php - Deleting multiple records in laravel using foreach loop

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!']);
}
question from:https://stackoverflow.com/questions/65870567/deleting-multiple-records-in-laravel-using-foreach-loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...