使用 foreach 循环删除 laravel 中的多条记录
Deleting multiple records in laravel using foreach loop
我正在尝试使用 product_id 删除多张图片,我可以一次删除一张图片,但我正在弄清楚如何将 $i=0 之类的变量插入到循环中,但它在 laravel 中不起作用。
到目前为止这是我的代码
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!']);
}
findOrFail
方法return只有一项。所以你不能迭代它。
您可以使用 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();
试试这个:
public function ImageDelete($slider_id)
{
$product = Products::find($slider_id);
$product_images=$product->images()->get();
foreach($product_images as $product_image){
$image_path = public_path().'\images2\'.$product_image->filename;
File::delete($image_path);
}
$product->delete();
return response()->json(['success'=>'Pics deleted successfully!']);
}
我正在尝试使用 product_id 删除多张图片,我可以一次删除一张图片,但我正在弄清楚如何将 $i=0 之类的变量插入到循环中,但它在 laravel 中不起作用。 到目前为止这是我的代码
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!']);
}
findOrFail
方法return只有一项。所以你不能迭代它。
您可以使用 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();
试试这个:
public function ImageDelete($slider_id)
{
$product = Products::find($slider_id);
$product_images=$product->images()->get();
foreach($product_images as $product_image){
$image_path = public_path().'\images2\'.$product_image->filename;
File::delete($image_path);
}
$product->delete();
return response()->json(['success'=>'Pics deleted successfully!']);
}