Laravel 8 E-Commerce - Delete Cart Item

In this video, we will learn about deleting products from the cart.

Let's see how we can achieve this. For deleting a cart product, let's create a function inside the CartComponent.php class file, located in the app/http/livewire directory.

Inside this file, let's create a function that deletes a product from the cart by its rowId:


public function destroy($rowId)
{
Cart::instance('cart')->remove($rowId);
session()->flash('success_message','Item has been removed');
}

Now, open the CartComponent view file and let's call the destroy function on the click event:


<div class="delete">
<a href="#" wire:click.prevent="destroy('{{$item->rowId}}')" class="btn btn-delete" title="">
<span>Delete from your cart</span>
<i class="fa fa-times-circle" aria-hidden="true"></i>
</a>
</div>

Now, let's check this. Switch to the browser and add some products to the cart.

For removing a product from the cart, let's click on the delete icon. And you can see that the item has been removed.

Now, let's remove another one. You can see that the product has been removed.

Next, let's create a function that empties all products from the cart. For that, go to the CartComponent.php class file.

And inside this file, let's create another function:


public function destroyAll()
{
Cart::instance('cart')->destroy();
session()->flash('success_message','All Item are removed');
}

Now, open the cart-component.blade.php view file and inside this link, simply call the function on the click event:


<div class="update-clear">
<a class="btn btn-clear" href="#" wire:click.prevent="destroyAll()">Clear Shopping Cart</a>
<a class="btn btn-update" href="#">Update Shopping Cart</a>
</div>

Now, let's check this. Switch to the browser and add some products to the cart. Then, click on the "Clear Shopping Cart" link.

Now, you can see that all products have been removed from the cart.

So, in this way, you can remove or empty the cart in a Laravel 8 e-commerce application.