In this video, we will learn about updating cart quantity.

Let's explore how to update the quantity in the cart.

Creating a Function to Update Cart Quantity

To update the cart quantity, let's create a function inside the CartController:


public function updateCart(Request $request)
{
Cart::instance('cart')->update($request->rowId,$request->quantity);
return redirect()->route('cart.index');
}

Creating a Route for the Function

Now, create a route for this function. Go to the web.php file and create a new route:


Route::put('/cart/update', [CartController::class, 'updateCart'])->name('cart.update');

Adding a Form to the Cart View

Now, go to the cart.blade.php file and add a form as follows:


<form id="updateCartQty" action="{{route('cart.update')}}" method="POST">
@csrf
@method('put')
<input type="hidden" id="rowId" name="rowId" />
<input type="hidden" id="quantity" name="quantity" />
</form>

Adding a JavaScript Function

Add the push directive inside the script tag and create a JavaScript function as follows:


@push('scripts')
<script>
function updateQuantity(qty)
{
$('#rowId').val($(qty).data('rowid'));
$('#quantity').val($(qty).val());
$('#updateCartQty').submit();
}
</script>
@endpush

Inside the input number field, add the data-rowid="{{$item->rowId}}".

Now, let's call this function using the onclick event from this input number field as follows:


<td>
<div class="qty-box">
<div class="input-group">
<input type="number" name="quantity" data-rowid="{{$item->rowId}}" onchange="updateQuantity(this)" class="form-control input-number" value="{{$item->qty}}">
</div>
</div>
</td>

Testing the Update Cart Quantity Functionality

It's done! Now, let's check this.

First, let's add a product to the cart.

Now, click on the up arrow to increase the product quantity by one.

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.

So, for that, just click on the down arrow.

Here, you can see that the number of products has been reduced.

If I click one more time on this down icon, then the item will be removed from the cart.

In this way, you can update the cart quantity in a Laravel 10 e-commerce project.