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;
}
}
In Cart Class
In Controller addToCart Function