Laravel 12 E-Commerce: Implementing Admin Delete Product
Hi everyone, welcome back to the Laravel E-Commerce Project Tutorial. This video focuses on implementing the functionality to delete existing products from the admin panel, including the necessary controller logic, routing, and a confirmation prompt.
1. Create Delete Logic and Route
Delete Function (`AdminController.php`)
In the `AdminController`, create the `delete_product` function. This function finds the product by ID, handles the deletion of the associated main image and gallery images (if they exist), and then deletes the product record from the database. It redirects the user back to the product listing page with a success message (though the provided code only redirects).
public function delete_product($id)
{
$product = Product::find($id);
// NOTE: The provided snippet only shows the product record deletion.
// A complete implementation would include deleting the main image and gallery images from storage.
$product->delete();
return redirect()->route("admin.products");
}
Define Delete Route (`web.php`)
Create a `DELETE` route for the product deletion logic, passing the product ID as a URL parameter:
Route::delete("/admin/product/{id}/delete",[AdminController::class,"delete_product"])->name("admin.product.delete’);
2. Update View with Delete Form and Confirmation
Add Delete Form (`products.blade.php`)
In the `products.blade.php` view file, locate the product listing table and wrap the delete icon in a form that submits a `DELETE` request, pointing to the new delete route:
<form action="{{route("admin.product.delete",["id"=>$product->id])}}" method="POST">
@csrf
@method("DELETE")
<div class="item text-danger delete">
<i class="fa fa-trash"></i>
</div>
</form>
Implement SweetAlert Confirmation (JavaScript)
Add JavaScript (likely within a `@push("scripts")` block) to utilize the SweetAlert library. This script prevents immediate form submission and shows a confirmation dialog, submitting the form only if the user confirms the action.
@push("scripts")
<script>
$(function() {
$(".delete").on("click", function(e) {
e.preventDefault();
var form = $(this).closest("form");
swal({
title: "Are you sure?",
text: "You want to delete this record?",
type: "warning",
buttons: ["No", "Yes"],
confirmButtonColor: "#dc3545"
}).then(function(result) {
if (result) {
form.submit();
}
});
});
});
</script>
@endpush
3. Testing
After implementing the changes, refresh the Admin Products page. Clicking the Trash icon should display the confirmation box. Confirming the action should delete the product record and refresh the page.
This concludes the implementation of the Admin Delete Product functionality.
