繁体   English   中英

Laravel Session 未存储新项目但正在覆盖

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM