Laravel会话不是存储新项目,但它的覆盖
我试图将新项目添加到会话容器中,如果可用旧项目,我将把新项目推到容器中。现在,每当我添加新项目时,都会通过替换上一项来存储当前项目,在控制器中,我的功能在哪些问题中
添加新项目
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 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;
}
}
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;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
购物车类中
在控制器addtocart函数中的
In Cart Class
In Controller addToCart Function