2016-11-25 18 views
0

カートに追加ボタンを押すたびに、古いカートが古いカートに新しいアイテムを追加するのではなく新しいものに置き換えられ、存在する場合は数量が更新されません。画像。これは私が現在、私を取得していますセッションイメージですlaravel 5.3ショッピングカートのセッションにアクセスする

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(); 

} 

私Cart.phpモデル

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; 
} 

}

私のルート

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

私のコントローラ知らないこのStoreオブジェクトは何ですか?私は名「カート」を介して

enter image description here

をアクセスするカント私が得るべき道は

enter image description here

を、以下のようなものです。これはのみにアクセスする方法DDメソッド内のすべてのセッションの目的でしたカート部分? enter image description here

ありがとうございます。

答えて

0

代わりLaravel documentationputとしてsession()->put()

$request->session()->push('cart', $cart); 

の使用session()->push()は透過性データを上書きしますとpushは、セッション配列に新しい値を追加します。

+0

まだ古いものと置き換えられません – hEShaN

0

スリップこの部分

dd($request->session())->get('cart'); 

それはあなたのカートのセッションをリセットしますので。 このようにこの機能を使用する

public function AddCart(Request $request, $id) 
{ 

    $product = Product::find($id); 
    if($request->session()->exists('cart')) 
    { 
     $oldCart = $request->session()->get('cart'); 
    } 
    else 
    { 
     $oldCart=false; 
    } 

    $Cart = new Cart($oldCart); 
    $Cart->Add($product, $id); 
    $request->session()->put('cart',$Cart); 
    return redirect()->back(); 
関連する問題