我有laravel 5.5项目,我制作了带有会话的购物车系统,正如我调试它,它工作正常并将产品添加到购物车但是在购物车视图中获取带有foreach的产品我有问题,这里是错误:
为foreach()提供的参数无效
这是我的刀片代码:
@if (Session::has('cart'))
@foreach($products as $product)
{{$product->title}}
@endforeach
@else
no product
@endif
这是我的Cart model
public $items;
public $totalQty = 0;
public $totalPrice = 0;
public function __construct($oldCart) {
if ($oldCart) {
$this->items = $oldCart->items;
$this->items = $oldCart->totalQty;
$this->items = $oldCart->totalPrice;
}
}
public function add($item, $id) {
$storedItem = ['qty' => 0, 'price' => $item->price, 'item' => $item];
if ($this->item) {
if (array_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;
}
这是我的CartController
public function AddToCart(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);
return redirect()->back();
}
public function index()
{
if (!Session::has('cart')) {
return view('frontend.cart');
}
$oldCart = Session::get('cart');
$cart = new Cart($oldCart);
return view('frontend.cart', ['products' => $cart->items, 'totalPrice' => $cart->totalPrice]);
}
这是我的路线:
//Cart
Route::resource('/cart', 'CartController', ['except' => ['show', 'create']]);
// Session route for add to cart
Route::get('/add-to-cart/{id}', [
'uses' => 'CartController@AddToCart',
'as' => 'product.addToCart'
]);
任何人都知道我的刀片循环问题是什么?
答案 0 :(得分:0)
看起来错误就在这里:
public function __construct($oldCart) {
if ($oldCart) {
$this->items = $oldCart->items;
$this->items = $oldCart->totalQty;
$this->items = $oldCart->totalPrice;
}
}
看起来$this->items = $oldCart->totalPrice;
是浮点值而不是数组。
也许应该是:
public function __construct($oldCart) {
if ($oldCart) {
$this->items = $oldCart->items;
$this->totalQty = $oldCart->totalQty;
$this->totalPrice = $oldCart->totalPrice;
}
}