I’m developing an e commerce website Laravel PHP. In my cart page when I click update quantity its suddenly coming again into previous quantity value. But this happen only in first product in cart products list. Second, third and for other all products this update quantity working properly. Whatever comes to first in cart products list, quantity value comes to previous value when click update button.
cart blade
[
@extends('layout')
@section('content')
<section class="container mx-auto py-16 px-4 lg:px-8">
<h1 class="text-3xl font-semibold mb-6">Shopping Cart</h1>
@if(empty($cart))
<p class="text-gray-500">Your cart is empty.</p>
<a href="/shop" class="text-blue-500">Continue Shopping</a>
<!-- Show total price (as zero) and proceed to checkout button even when the cart is empty -->
<div class="mt-6">
<p class="text-xl font-semibold">Total Price: <span class="text-green-500">LKR0.00</span></p>
</div>
<button
class="bg-yellow-500 text-white px-6 py-3 rounded-lg mt-6 block text-center opacity-50 cursor-not-allowed"
disabled>
Proceed to Checkout
</button>
@else
<!-- Form to handle selected products -->
<form action="{{ route('checkout.show') }}" method="GET" id="checkout-form">
<table class="w-full text-left border-collapse">
<thead>
<tr>
<th class="border-b py-4">Select</th>
<th class="border-b py-4">Image</th>
<th class="border-b py-4">Name</th>
<th class="border-b py-4">Price</th>
<th class="border-b py-4">Quantity</th>
<th class="border-b py-4"></th>
</tr>
</thead>
<tbody id="cart-items">
@foreach($cart as $productId => $item)
<tr>
<td class="py-4">
<input type="checkbox" name="selected[]" class="product-checkbox" value="{{ $productId }}" data-price="{{ $item['price'] * $item['quantity'] }}" onchange="updateTotalPrice()">
</td>
<td class="py-4">
<img src="{{ asset('storage/' . $item['image']) }}" alt="{{ $item['name'] }}" class="w-20">
</td>
<td class="py-4">{{ $item['name'] }}</td>
<td class="py-4">LKR{{ number_format($item['price'], 2) }}</td>
<td class="py-4">
<form action="{{ route('cart.update', $productId) }}" method="POST">
@csrf
@method('PUT')
<input type="number" name="quantity" value="{{ $item['quantity'] }}" min="1" class="border border-gray-300 rounded px-4 py-2 w-20">
<button type="submit" class="text-blue-500 hover:text-blue-700 ml-2">Update</button>
</form>
</td>
<td class="py-4">
<form action="{{ route('cart.remove', $productId) }}" method="POST">
@csrf
@method('DELETE')
<button type="submit" class="text-red-500 hover:text-red-700">Remove</button>
</form>
</td>
</tr>
@endforeach
</tbody>
</table>
<div class="mt-6">
<p class="text-xl font-semibold">
Selected Total Price: <span class="text-green-500" id="selected-total">LKR0.00</span>
</p>
</div>
<form action="{{ route('cart.clear') }}" method="POST" class="mt-4">
@csrf
<button type="submit" class="text-red-500 hover:text-red-700">Clear Cart</button>
</form>
<!-- Submit button to proceed to checkout -->
<button type="submit"
class="bg-yellow-500 text-white px-6 py-3 rounded-lg mt-6 block text-center opacity-50 cursor-not-allowed"
id="checkout-button"
disabled>
Proceed to Checkout
</button>
</form>
@endif
</section>
<script>
function updateTotalPrice() {
let totalPrice = 0;
let isSelected = false; // Flag to check if at least one checkbox is selected
document.querySelectorAll('.product-checkbox').forEach(checkbox => {
if (checkbox.checked) {
totalPrice += parseFloat(checkbox.dataset.price);
isSelected = true; // Set flag to true if any checkbox is selected
}
});
// Update total price
document.getElementById('selected-total').innerText = 'LKR' + totalPrice.toFixed(2);
// Enable or disable the Proceed to Checkout button based on selection
const checkoutButton = document.getElementById('checkout-button');
if (isSelected) {
checkoutButton.classList.remove('opacity-50', 'cursor-not-allowed');
checkoutButton.classList.add('opacity-100', 'cursor-pointer');
checkoutButton.removeAttribute('disabled');
} else {
checkoutButton.classList.add('opacity-50', 'cursor-not-allowed');
checkoutButton.classList.remove('opacity-100', 'cursor-pointer');
checkoutButton.setAttribute('disabled', true);
}
}
document.querySelectorAll('.update-button').forEach(button => {
button.addEventListener('click', function () {
const productId = this.getAttribute('data-product-id');
const quantityInput = document.querySelector(`.quantity-input[data-product-id="${productId}"]`);
const quantity = quantityInput.value;
fetch(`/cart/update/${productId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
},
body: JSON.stringify({ quantity: quantity })
})
.then(response => response.json())
.then(data => {
if (data.success) {
// Update the total price in the checkbox's data attribute
const productCheckbox = document.querySelector(`.product-checkbox[value="${productId}"]`);
productCheckbox.dataset.price = data.updatedPrice;
// Recalculate the total price
updateTotalPrice();
alert(data.message);
} else {
alert('Failed to update the cart.');
}
})
.catch(error => {
console.error('Error:', error);
});
});
});
</script>
@endsection
]
controller
[
<?php
namespace AppHttpControllers;
use AppModelsProduct;
use IlluminateHttpRequest;
use IlluminateSupportFacadesSession;
class CartController extends Controller
{
/**
* Add product to the cart.
*/
public function addToCart(Request $request)
{
// Get the cart from the session, or initialize an empty array if not set
$cart = Session::get('cart', []);
// Retrieve the product data from the request
$productId = $request->input('product_id');
$productName = $request->input('name');
$productPrice = $request->input('price');
$productImage = $request->input('image');
$quantity = (int) $request->input('quantity', 1);
// Validate the product data
if (!$productId || !$productName || !$productPrice || !$productImage || $quantity < 1) {
return response()->json([
'success' => false,
'message' => 'Invalid product information.',
]);
}
// If the product is already in the cart, update the quantity
if (isset($cart[$productId])) {
$cart[$productId]['quantity'] += $quantity; // Increment quantity
} else {
// Otherwise, add the product to the cart
$cart[$productId] = [
'name' => $productName,
'price' => $productPrice,
'image' => $productImage,
'quantity' => $quantity,
];
}
// Save the updated cart back to the session
Session::put('cart', $cart);
// Get updated cart count
$cartCount = array_sum(array_column($cart, 'quantity'));
return response()->json([
'success' => true,
'message' => 'Product added to cart!',
'cartCount' => $cartCount, // Return the updated cart count
]);
}
/**
* Show the cart page.
*/
public function showCart()
{
$cart = Session::get('cart', []);
$totalPrice = 0;
foreach ($cart as $item) {
$totalPrice += $item['price'] * $item['quantity'];
}
return view('cart', ['cart' => $cart, 'totalPrice' => $totalPrice]);
}
/**
* Remove a product from the cart.
*/
public function removeFromCart($productId)
{
$cart = Session::get('cart', []);
// Check if the product exists in the cart
if (isset($cart[$productId])) {
// Remove the product from the cart
unset($cart[$productId]);
// Save the updated cart to the session
Session::put('cart', $cart);
}
// Redirect back to the cart page
return redirect()->route('cart.show');
}
/**
* Clear the entire cart.
*/
public function clearCart()
{
// Clear the cart from the session
Session::forget('cart');
// Redirect back to the cart page with a success message
return redirect()->route('cart.show')->with('success', 'Cart has been cleared!');
}
/**
* Update the quantity of a product in the cart.
*/
public function updateCart(Request $request, $productId)
{
$cart = Session::get('cart', []);
// Validate product ID and quantity
$quantity = (int) $request->input('quantity');
if (!isset($cart[$productId]) || $quantity < 1) {
return redirect()->route('cart.show')->with('error', 'Invalid product or quantity.');
}
// Update the quantity in the cart
$cart[$productId]['quantity'] = $quantity;
// Save updated cart to session
Session::put('cart', $cart);
return redirect()->route('cart.show')->with('success', 'Cart updated successfully!');
}
/**
* Get the total count of products in the cart.
*/
public function getCartCount()
{
$cart = session()->get('cart', []);
$count = array_sum(array_column($cart, 'quantity'));
return response()->json(['count' => $count]);
}
}
]
I tried change update method in controller, but didnt work.