При добавлении любого товара в продукт, добавляется последний. Почему так происходит?
public function addToCart(Request $request)
{
$id = $request->get('id');
$product = Product::findOrFail($id);
$cart = session()->get('cart', []);
if(!empty($cart[$id])) {
$cart[$id]['quantity']++;
} else {
$cart[$id] = [
'id' => $product->id,
"title" => $product->title,
"quantity" => 1,
"price" => $product->price,
];
}
session()->put('cart', $cart);
return redirect()->back()->with('success', 'Product added to cart successfully!' . $id );
}
public function update(Request $request)
{
if($request->id && $request->quantity){
$cart = session()->get('cart');
$cart[$request->id]["quantity"] = $request->quantity;
session()->put('cart', $cart);
session()->flash('success', 'Cart updated successfully');
}
}
@foreach ($products as $product)
<div class="product">
<div class="product-photo">
<img src="https://loremflickr.com/210/210" alt="" width="210px" height="210px">
</div>
<div class="product-content">
<span class="product-title">{{ $product->title }}</span>
<div class="product-bottom">
<div class="product-price">{{ number_format($product->price, 2, '.', '') }}</div>
<div class="product-button">
<form action="{{ route('cart.add') }}" method="post">
@csrf
<input type="hidden" name="id" value="{{ $product->id }}">
<button type="submit"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-cart-plus" viewBox="0 0 16 16">
<path d="M9 5.5a.5.5 0 0 0-1 0V7H6.5a.5.5 0 0 0 0 1H8v1.5a.5.5 0 0 0 1 0V8h1.5a.5.5 0 0 0 0-1H9V5.5z" />
<path d="M.5 1a.5.5 0 0 0 0 1h1.11l.401 1.607 1.498 7.985A.5.5 0 0 0 4 12h1a2 2 0 1 0 0 4 2 2 0 0 0 0-4h7a2 2 0 1 0 0 4 2 2 0 0 0 0-4h1a.5.5 0 0 0 .491-.408l1.5-8A.5.5 0 0 0 14.5 3H2.89l-.405-1.621A.5.5 0 0 0 2 1H.5zm3.915 10L3.102 4h10.796l-1.313 7h-8.17zM6 14a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm7 0a1 1 0 1 1-2 0 1 1 0 0 1 2 0z" />
</svg>
</button>
</div>
</div>
</div>
</div>
@endforeach
@if(session('cart'))
@foreach(session('cart') as $id => $details)
<div class="row cart-detail">
<div class="col-lg-8 col-sm-8 col-8 cart-detail-product">
<p>{{ $details['id'] }}</p>
<p>{{ $details['title'] }}</p>
<span class="price text-info"> ${{ $details['price'] }}</span> <span class="count"> Quantity:{{ $details['quantity'] }}</span>
</div>
</div>
@endforeach
@endif