Laravel 11 E-Commerce - Update Cart Quantity

Welcome back to the Laravel E-Commerce Tutorial. In this video, we will learn about updating the quantity in the cart.

Step 1: Create Functions for Increasing and Decreasing Quantity

To update the cart quantity, we will create two functions: one for increasing the quantity and another for decreasing the cart quantity. Go to the CartController and add the following functions:


public function increase_item_quantity($rowId)
{
$product = Cart::instance('cart')->get($rowId);
$qty = $product->qty + 1;
Cart::instance('cart')->update($rowId,$qty);
return redirect()->back();
}

public function reduce_item_quantity($rowId){
$product = Cart::instance('cart')->get($rowId);
$qty = $product->qty - 1;
Cart::instance('cart')->update($rowId,$qty);
return redirect()->back();
}

Step 2: Create a Route for the Component

Create a new route for the component by going to the web.php file:


Route::put('/cart/increase-qunatity/{rowId}',[CartController::class,'increase_item_quantity'])->name('cart.increase.qty');
Route::put('/cart/reduce-qunatity/{rowId}',[CartController::class,'reduce_item_quantity'])->name('cart.reduce.qty');

Step 3: Add Form to the Cart View

Go to the cart.blade.php file and add a form for the increase and decrease quantity buttons:


<td>
<div class="qty-control position-relative">
<input type="number" name="quantity" value="{{$cartItem->qty}}" min="1" class="qty-control__number text-center">
<form method="POST" action="{{route('cart.reduce.qty',['rowId'=>$cartItem->rowId])}}">
@csrf
@method('PUT')
<div class="qty-control__reduce">-</div>
</form>
<form method="POST" action="{{route('cart.increase.qty',['rowId'=>$cartItem->rowId])}}">
@csrf
@method('PUT')
<div class="qty-control__increase">+</div>
</form>
</div>
</td>

Step 4: Add Script for Increasing and Decreasing Quantity

Add the following script to the cart.blade.php file:

@push("scripts") @endpush

Final Step: Check the Cart Quantity

Now, let's check the cart quantity. First, add a product to the cart. Click on the up arrow to increase the product quantity by one. You can see that the number of products has increased by one, and the subtotal and total price have also increased. Now, let's decrease the product quantity. Click on the down arrow. You can see that the number of products has decreased. If you click one more time on the down icon, the item will be removed from the cart. In this way, you can update the cart quantity.

That's all about updating the cart quantity.