Laravel 12 E-Commerce: Implementing Delete and Clear Cart Item

Hi everyone, welcome back to the Laravel E-Commerce Project Tutorial. This video covers the steps for implementing the functionality to delete a single product and clear all products from the shopping cart.


1. Delete Single Cart Item Logic and Route

To delete a single item, we will create a controller function that uses the product'sunique `rowId` from the cart package.

Remove Item Function (`CartController.php`)

The function uses the `remove()` method on the cart instance, passing the `rowId` of the item to be deleted:

public function remove_item_from_cart($rowId)
{
Cart::instance("cart")->remove($rowId);
return redirect()->back();
}

Define Route for Deleting Item (`web.php`)

Create a `DELETE` route that accepts the `rowId` as a parameter:

Route::delete("/cart/remove/{rowId}",[CartController::class,"remove_item_from_cart"])->name("cart.remove");

Update Cart View for Deletion (`cart.blade.php`)

In the product listing table, wrap the trash icon in a form that submits a `DELETE` request to the new route:

<td class="product-action">
<form method="POST" action="{{ route("cart.remove", ["rowId" => $item->rowId]) }}">
@csrf
@method("DELETE")
<button class="remove" type="submit">
<i class="pe-7s-trash"></i>
</button>
</form>
</td>

2. Clear All Cart Items Logic and Route

To clear the entire cart, we will use the `destroy()` method provided by the cart package.

Empty Cart Function (`CartController.php`)

public function empty_cart()
{
Cart::instance("cart")->destroy();
return redirect()->back();
}

Define Route for Clearing Cart (`web.php`)

Create a `DELETE` route to trigger the cart clearing logic:

Route::delete("/cart/clear",[CartController::class,"empty_cart"])->name("cart.empty");

Update Cart View for Clearing Cart (`cart.blade.php`)

Add a form around the "Clear Cart" button to submit a `DELETE` request to the appropriate route:

<div class="cart-btn">
<div class="left-btn">
<a href="{{ route("shop.index") }}" class="btn btn-dark btn-hover-primary">Continue Shopping</a>
</div>
<div class="right-btn">
<form action="{{ route("cart.empty") }}" method="POST">
@csrf
@method("DELETE")
<button class="btn btn-outline-dark" type="submit">Clear Cart</button>
</form>
</div>
</div>

3. Testing the Functionality

After implementing the changes, test the deletion and clearing features:

  • Click the Trash icon next to a product to confirm it is deleted and the cart totals are updated.
  • Click the Clear Cart button to confirm all products are removed and the cart becomes empty.

This concludes the implementation of the delete and clear cart item functionality.