'Laravel Session is not storing new items but it's overwriting

I was trying to add new items to a session container, and if old items are available then I'll just push the new items to the container. Now whenever I'm adding new items it's storing the current item by replacing the previous item, where is the issue?

In Controller my function to add new items

public function addToCart($id)
{
    $product = Product::findOrFail($id);

    $oldCart = Session::has("cart") ? Session::get("cart") : null;

    $cart = new Cart($oldCart);

    $cart->addNewItem($id, $product);

    Session::put("cart", $cart);

    dd(Session::get("cart"));
}

In Class

class Cart
{
    public $items = null;
    public $totalQty = 0;
    public $totalPrice = 0;

    public function __construct($oldCart)
    {
        if ($oldCart) {
            $this->items = $oldCart->items;
            $this->totalQty = $oldCart->totalQty;
            $this->totalPrice = $oldCart->totalPrice;
        }
    }

    public function addNewItem($id, $item)
    {
        $storeNewItem["product_id"] = $item->id;
        $storeNewItem["product_name"] = $item->product_name;
        $storeNewItem["product_price"] = $item->product_price;

        $this->totalQty++;
        $this->totalPrice += $item->product_price;
        $this->items[$id] = $storeNewItem;
    }
}


Solution 1:[1]

In Cart Class

public function addNewItem($id,$item) {
    
    $storeNewItem["product_id"] = $item->id;
    $storeNewItem["product_name"] = $item->product_name;
    $storeNewItem["product_price"] = $item->product_price;

    $this->totalQty++;
    $this->totalPrice += $item->product_price;

    return [
             'totalQty', => $this->totalQty,
             'totalPrice', => $this->totalPrice,
             'items[$id]', => $storeNewItem,
           ]

}

In Controller addToCart Function

$newCart = $cart->addNewItem($id,$product);

Session::put("cart",$newCart );

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anuj Kumar