Laravel Multiple Image Delete Process
// Function to delete product and its associated images
public function deleteProduct($productId)
{
// Find the product by its ID
$product = Product::findOrFail($productId);
// Define the paths for all associated images
$imagePaths = [
public_path('images/' . $product->product_thumbnail),
public_path('uploads/product-gallery/' . $product->prod_gal_img_one),
public_path('uploads/product-gallery/' . $product->prod_gal_img_two),
public_path('uploads/product-gallery/' . $product->prod_gal_img_three),
public_path('uploads/product-gallery/' . $product->prod_gal_img_four),
];
// Loop through the image paths and delete if file exists
foreach ($imagePaths as $imagePath) {
if (file_exists($imagePath)) {
unlink($imagePath);
}
}
// Delete the product from the database
$product->delete();
return redirect()->route('admin.products')->with('success', 'Product Deleted successfully.');
}
public function destroy($id)
{
return $this->deleteProduct($id);
}
No comments