简体   繁体   English

使用Laravel会话添加到购物车

[英]Add to Cart Using Laravel Session

I am using laravel sessions to store cart information on the web browser but I am getting this error "Trying to get property of a non object" when am testing. 我正在使用laravel会话在网络浏览器上存储购物车信息,但是在测试时却收到此错误“试图获取非对象的属性”。 Any insights? 有什么见解吗? the first snippet is controller then my model.I am using two foreach to retrieve the product information then display them on a modal where a user can now add to cart. 第一个代码段是控制器,然后是我的模型。我正在使用两个foreach来检索产品信息,然后以模态显示它们,用户现在可以将其添加到购物车中。

  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); dd($request->session()->get('cart')); return redirect()->back()->with('flash_message_success', 'Added Successfully'); } 

<?php

namespace App;

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 add($item,$id){
        $storedItem = ['qty'=>0, 'price' =>$item->price, 'item' ->$item->item];

        if ($this->items) {
            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; 
    }
}

Product::find($id), the passed Id probably doesn't exists in your table. Product :: find($ id),您的表中可能不存在传递的ID。 Make sure to pass an actual record. 确保通过实际记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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