I need to increase the value of the variable when i click on a button but the the value is always one. i had clicked the button to more than five times but still the result is always 1.please see the attached image.
my cart class
class Cart
{
public $totalQuantity = 0;
public function __construct($oldCart)
{
if ($oldCart) {
$this->totalQuantity = $oldCart->totalQuantity;
}
}
public function add()
{
$this->totalQuantity++;
}
}
controller method
public function getAddToCart(Request $request,$id){
$oldCart=null;
//code that i added now to check which returns null
dd($request->session()->get('cart'));
if($request->session()->pull('cart')) {
$oldCart=$request->session()->pull('cart') ;
}
$cart=new Cart($oldCart);
$cart->add();
$request->session()->push('cart',$cart);
dd($request->session()->pull('cart'));
return redirect()->back();
}
following is the image
Laravel doc:
The pull method will retrieve and delete an item from the session in a single statement
So if you pull it in the if statetment than the second pull has nothing to offer you as you already deleted it :). You should use get instead, or pull it directly in the $oldCart variable.
Oh and also if you use push method it is stored as an array so your code should look like this:
$oldCart = $request->session()->pull('cart');
if ($oldCart) {
$cart = new Cart($oldCart[0]);
} else {
$cart = new Cart(null);
}
$cart->add();
$request->session()->push('cart',$cart);
or even better like this:
$oldCart = null;
if ($request->session()->has('cart')) {
$oldCart = $request->session()->get('cart');
}
$cart = new Cart($oldCart);
$cart->add();
$request->session()->put('cart',$cart);