[英]Laravel Session is not storing new items but it's overwriting
我試圖將新項目添加到 session 容器中,如果舊項目可用,那么我將把新項目推送到容器中。 現在,每當我添加新項目時,它都會通過替換前一個項目來存儲當前項目,問題出在哪里?
在Controller我的function添加新項目
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"));
}
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;
}
}
在購物車 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,
]
}
加入購物車 Controller Function
$newCart = $cart->addNewItem($id,$product);
Session::put("cart",$newCart );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.