Laravel 11 E-Commerce - Admin Delete Product

Welcome back to the Laravel E-Commerce Project Tutorial! In this video, we are going to learn about deleting a product.

Creating the Delete Function

So, let's see how we can delete the product. First of all, go to the AdminController and create a function here:


public function delete_product($id)
{
$product = Product::find($id);
$product->delete();
return redirect()->route('admin.products')->with('status','Record has been deleted successfully !');
}

Creating the Route

Now, let's create the route for this function. So, go to the web.php file and create a new route:


Route::delete('/admin/product/{id}/delete',[AdminController::class,'delete_product'])->name('admin.product.delete');

Adding the Delete Link

Now, go to the products.blade.php and add a link for deleting the product. So, inside the foreach, add here:


<form action="{{route('admin.product.delete',['id'=>$product->id])}}" method="POST">
@csrf
@method('DELETE')
<div class="item text-danger delete">
<i class="icon-trash-2"></i>
</div>
</form>

Displaying the Confirmation Dialog Box

Now, in the products.blade.php file, add the @push directive and for displaying the confirmation dialog box before deleting:


@push('scripts')
<script>
$(function(){
$(".delete").on('click',function(e){
e.preventDefault();
var selectedForm = $(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) {
selectedForm.submit();
}
});
});
});
</script>
@endpush

Checking the Result

Now, let's check this. So, refresh the page. Now, let's delete any product from this list. Click on the delete link, and you can see the confirmation dialog box. Now, click on delete, and you can see the product has been deleted.

So, in this way, you can delete the product. That's all about deleting the product.