Laravel 11 E-Commerce - Delete and Clear Cart Item

Welcome back to the Laravel E-Commerce Tutorial. In this video, we will learn about deleting and clearing products from the cart.

Step 1: Create a Function to Delete a Cart Product

To delete a cart product, let's create a function inside the CartController. Go to the CartController and create a function to delete a product from the cart by rowId:


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

Step 2: Create a Route for the Function

Create a route for the function:


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

Step 3: Create a Form to Delete a Cart Product

Create a form to delete a cart product:


<td>
<form method="POST" action="{{route('cart.remove',['rowId'=>$cartItem->rowId])}}">
@csrf
@method("DELETE")
<a href="javascript:void(0)" class="remove-cart">
<svg width="10" height="10" viewBox="0 0 10 10" fill="#767676" xmlns="http://www.w3.org/2000/svg">
<path d="M0.259435 8.85506L9.11449 0L10 0.885506L1.14494 9.74056L0.259435 8.85506Z" />
<path d="M0.885506 0.0889838L9.74057 8.94404L8.85506 9.82955L0 0.97449L0.885506 0.0889838Z" />
</svg>
</a>
</form>
</td>

Step 4: Submit the Form Using JavaScript

Submit the form using a JavaScript function:


@push("scripts")
<script>
$(function(){
$('.remove-cart').on("click",function(){
$(this).closest('form').submit();
});
});
</script>
@endpush

Step 5: Create a Function to Empty the Cart

Let's create another function to empty all products from the cart. Go to the CartController and create a function:


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

Step 6: Create a Route for the Function

Create a route for the function:


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

Step 7: Add a Button to Empty the Cart

Go to the cart.blade.php file and add a button to empty the cart:


<form class="position-relative bg-body" method="POST" action="{{route('cart.empty')}}">
@csrf
@method('DELETE')
<button class="btn btn-light" type="submit">CLEAR CART</button>
</form>

Final Step: Check the Cart

Now, let's check the cart. Switch to the browser, add some products to the cart, and click on "Clear all Items". You can see that all products have been removed from the cart. In this way, you can delete or empty cart items.

That's all about deleting and clearing cart items.