vendredi 25 novembre 2016

laravel 5.3 session accessing for shopping cart

Every time i press add to cart button the old cart replaces the new one rather than adding the new item to old cart and it doesnt update the quantity if it is present.Following are the codes and the images.

my Cart.php Model

class Cart{

public $spares=null;
public $totalQuantity=0;
public $totalPrice=0;

public function __construct($oldCart){
    if($oldCart){
        $this->spares=$oldCart->spares;
        $this->totalPrice=$oldCart->totalQuantity;
        $this->totalQuantity=$oldCart->totalQuantity;
    }
    else{
        $this->spares=null;
    }

}

public function add($spare,$id){
     $storedItem=['qty' => 0,'price'=>$spare->price,'item'=>$spare];
    if($this->spares){
        if(array_key_exists($id,$this->spares)){
            $storedItem=$this->spares[$id];
        }
    }
    $storedItem['qty']++;
    $storedItem['price']= $spare->price*$storedItem['qty'];
    $this->spares[$id]=$storedItem;
    $this->totalQuantity++;
    $this->totalPrice+=$spare->price;
}

}

my route

Route::get('/addToCart/{id}',['uses'=>'searchController@getAddToCart',
'as'=>'product.addToCart'] );

my controller

 public function getAddToCart(Request $request,$id){
     $spares=Spares::find($id);
     $oldCart=Session::has('cart')? Session::get('cart'):null;
     $cart=new Cart($oldCart);
     $cart->add($spares,$spares->id);

     $request->session()->put('cart',$cart);
     dd($request->session())->get('cart');
     return redirect()->back();

 }

This is the session image that i am currently getting

enter image description here

The way that i should get is like following

enter image description here

Thank you very much in advance.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire