简体   繁体   中英

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. 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.

  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. Make sure to pass an actual record.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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