即时通讯使用laravel 5.3,该项目正在推车 单击项目时,数量不会增加
产品控制
public function getAddToCart(Request $request, $id)
{
$product =Product::find($id);
$oldcart = Session::has('cart') ? Session::get('cart') : null;
$cart = new Cart($oldcart);
$cart->add($product , $product->id);
$request->session()->put('cart',$cart);
// TO show it dd($request->Session()->get('cart'));
return redirect()->route('product.index');
}
和模型Cart:
class Cart
{
public $items = null;
public $totalQty = 0;
public $totalPrice = 0;
public function __consruct($oldCart){
if($oldCart){
$this->$items = $oldCart->items;
$this->$totalQty = $oldCart->totalQty;
$this ->$totalPrice = $oldCart->totalPrice;
}
}
public function add($item,$id){
$storedItem = ['qty' => 0,'price' => $item->price,'item' => $item];
if ($this->items)
{
if(arrary_Key_exists($id,$this->items))
{
$storedItem = $this->items[$id];
}
}
$storedItem['qty']++;
$storedItem['price'] = $item->price * $storedItem['qty'];
$this->items[$id] = $storedItem;
$this->totalQty++;
$this->totalPrice += $item->price;
}
}
这是一个产品页面:
<a href="#"> <i class="fa fa-shopping-cart" aria-hidden="true"></i> Shopping Cart
<span class="badge">{{ Session::has('cart') ? Session::get('cart')->totalQty : '' }}</span>
</a>
它应该添加项目和增量,但它只显示项目的ID而不增加它。
答案 0 :(得分:0)
会话保存为闪存数据。因此,您需要在推送数据时保存会话。由于你没有在你的代码中执行它总是得到一个新的购物车,第一项被添加到它,我认为你将这个数字与ID混淆,因为totalQty总是1。
因此请在将购物车对象放入会话后执行以下操作。
$request->session()->save();
答案 1 :(得分:0)
你的意思是
array:4 [▼
"_token" => "NaciZTnMzNzqB02Nvr7RtXJj7c5NtsUF339522l2"
"_previous" => array:1 [▼
"url" => "http://localhost:8000"
]
"_flash" => array:2 [▼
"old" => []
"new" => []
]
Cart {#163 ▼
+items: array:1 [▼
1 => array:3 [▼
"qty" => 1
"price" => 20
"item" => Product {#172 ▼
#fillable: array:4 [▼
0 => "imgaePath"
1 => "title"
2 => "description"
3 => "price"
]
#connection: null
#table: null
#primaryKey: "id"
#keyType: "int"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:7 [▼
"id" => 1
"created_at" => null
"updated_at" => null
"imagePath" => "http://www.abebooks.com/images/books/harry-potter/deathly-hallows.jpg"
"title" => "hurry potter"
"description" => "the best book ever"
"price" => 20
]
#original: array:7 [▼
"id" => 1
"created_at" => null
"updated_at" => null
"imagePath" => "http://www.abebooks.com/images/books/harry-potter/deathly-hallows.jpg"
"title" => "hurry potter"
"description" => "the best book ever"
"price" => 20
]
#relations: []
#hidden: []
#visible: []
#appends: []
#guarded: array:1 [▼
0 => "*"
]
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
+exists: true
+wasRecentlyCreated: false
}
]
]
+totalQty: 1
+totalPrice: 20
}