Laravel 12 E-Commerce: Implementing Admin Delete Brand

Hi everyone, welcome back to the Laravel E-Commerce Project Tutorial. This video focuses on implementing the functionality to delete existing brands in the admin panel, including image deletion and a confirmation prompt.


1. Create Delete Logic and Route

Delete Function (`AdminController.php`)

In the `AdminController`, create the `brand_delete` function. This function finds the brand by ID, deletes the associated image file from the server if it exists, and then deletes the brand record from the database. Finally, it redirects back to the brands list with a success message.

public function brand_delete($id)
{
$brand = Brand::find($id);
if(File::exists(public_path("uploads/brands") . "/" . $brand->image)) {
File::delete(public_path("uploads/brands") . "/" . $brand->image);
}
$brand->delete();
return redirect()->route("admin.brands")->with("status", "Brand has been deleted successfully!");
}

Define Delete Route (`web.php`)

Create a `DELETE` route for the brand deletion logic, specifying the ID in the URL:

Route::delete("/admin/brand/{id}/delete",[AdminController::class,"delete_brand"])->name("admin.brand.delete’);

2. Update View with Delete Form and Confirmation

Add Delete Form (`brands.blade.php`)

In the `brands.blade.php` view, wrap the delete icon in a form that submits a `DELETE` request, pointing to the new delete route. The link itself will trigger the form submission via JavaScript.

<form action="{{route("admin.brand.delete",["id"=>$brand->id])}}" method="POST">
@csrf
@method("DELETE")
<a href="javascript:void(0)" class="item text-danger delete">
<i class="fa fa-trash"></i>
</a>
</form>

Implement SweetAlert Confirmation

Use JavaScript with a library like SweetAlert (as the file suggests it'salready included) to display a confirmation message before the form is submitted. This prevents accidental deletion.

@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

Refresh the Brands page in the admin panel and click the trash icon next to a brand. A confirmation box should appear. Clicking Yes will submit the form, delete the brand and its image, and refresh the page with a success message.

This completes the brand deletion functionality.