Laravel 8 E-Commerce - Update Cart Quantity
In this video, we will learn about updating the cart quantity.
Let's see how we can achieve this. For increasing and decreasing the product quantity, let's create two functions inside the CartComponent class file. One function will be for increasing the product quantity, and another for decreasing the product quantity.
Switch to the project and go inside the app\http\livewire directory, then open the CartComponent.php file:
public function increaseQuantity($rowId)
{
$product = Cart::instance('cart')->get($rowId);
$qty = $product->qty + 1;
Cart::instance('cart')->update($rowId,$qty);
}
public function decreaseQuantity($rowId)
{
$product = Cart::instance('cart')->get($rowId);
$qty = $product->qty - 1;
Cart::instance('cart')->update($rowId,$qty);
}
Inside this file, let's create the functions. Now, let's call these functions on the click event of the + and - icons.
For that, just go to the Cart-Component view file and inside the increase link, add the increaseQuantity function and pass the rowId as an argument:
And inside the reduce link, add the decreaseQuantity function and pass the rowId as an argument:
<div class="quantity-input">
<input type="text" name="product-quatity" value="{{$item->qty}}" data-max="120" pattern="[0-9]*" >
<a class="btn btn-increase" href="#" wire:click.prevent="increaseQuantity('{{$item->rowId}}')"></a>
<a class="btn btn-reduce" href="#" wire:click.prevent="decreaseQuantity('{{$item->rowId}}')"></a>
</div>
Now, it's done. Let's check this. First, let's add a product to the cart.
Now, click on the + icon to increase the product quantity by one. Just click here:
You can see that the number of products has been increased by one, and the subtotal and total price have also been updated.
Now, let's decrease the product quantity. For that, just click on the - icon. Here, you can see that the number of product items has been reduced.
If I click one more time on this - icon, the item will be removed from the cart.
So, in this way, you can update the cart quantity in a Laravel 8 e-commerce project.