i have this issue in laravel 9.19 php 8.1 when i delete any image from the product it works, except deleting the first image that deletes the whole product. //products/edit.blade
<div class="d-flex flex-wrap">
@foreach($product->images as $image)
<div class="m-2">
@php echo route('products.images.destroy', [$product->id, $image->id])@endphp
<img src="{{ asset('storage/' . $image->image_url) }}" class="img-thumbnail"
style="width: 150px; height: 150px;" alt="">
<form action="{{ route('products.images.destroy', [$product->id, $image->id]) }}"
method="POST" style="display: inline-block;">
@csrf
@method('DELETE')
<button type="submit"
class="btn btn-danger btn-sm">{{ __('messages.delete') }}</button>
</form>
</div>
@endforeach
</div>
public function destroyImage($productId, $imageId)
{
// Check if the image exists
$image = ProductImage::where('product_id', $productId)
->where('id', $imageId)
->first();
if (!$image) {
return redirect()->route('products.edit', $productId)
->withErrors(__('messages.image_not_found'));
}
// Delete the image file from storage
Storage::delete($image->image_url);
// Delete the image record from the database
$image->delete();
return redirect()->route('products.edit', $productId)->with('success', __('messages.image_deleted_successfully'));
}
public function destroy($id)
{
$product = Product::findOrFail($id);
// Delete associated images
foreach ($product->images as $image) {
Storage::delete('public/products/' . $image->image_url);
$image->delete();
}
// Delete translations
$product->translations()->delete();
// Delete the product
$product->delete();
return redirect()->route('products.index')
->with('success', __('messages.product_deleted'));
}
Route::middleware(['custom.auth'])->group(function () {
// Categories (CRUD)
Route::resource('categories', CategoryController::class);
// Route to delete a specific product image
Route::delete('/images/{product}/{image}', [ProductController::class, 'destroyImage'])
->name('products.images.destroy');
// Ensure this comes after the above route
Route::resource('products', ProductController::class);
});
i tried to delete a specific image from the product, it works but deleting the first image points to the destroy
method instead of the destroyImage
method