1

i am making an e commerce shopping cart where i have used session to store cart item. But the problem is when i am trying to update (increase or decrease) cart item's quantity i am not getting the accurate total price. i am trying to update the whole cart not by single item...

This is update function in cart Model

    public function update($id, $qty){
        //reset qty and price in the cart
        $this->totalQty -= $this->items[$id]['qty'];
        $this->totalPrice -= $this->items[$id]['price'] * $this->items[$id]['qty'];

        //add item with new qty
        $this->items[$id]['qty'] = $qty;

        //total price and total qty in cart
        $this->totalQty += $qty;
        $this->totalPrice += $this->items[$id]['price'] * $qty;
    }

This is update function in controller

    //update cart
    public function updateQty(Request $request){
        $id = $request->item_id;
        $qty = $request->qty;

        $oldCart = Session::has('cart') ? Session::get('cart') : null;

        $cart = new Cart($oldCart);

        for ($i=0; $i <count($id) ; $i++) { 
            $cart->update($id[$i], $qty[$i]);
            Session::put('cart', $cart);
        }


        return redirect()->back();
    }

The cart

cart image in browser

Community
  • 1
  • 1
Rajin
  • 3
  • 3

1 Answers1

0

This should go outside the for loop.

Session::put('cart', $cart);

I will be surprised if this solves your problem but definitely something that you need to fix.

Also I don't understand the echo part in your for loop. Remove the echo and give it a try.

echo($cart->update($id[$i], $qty[$i]));
$cart->update($id[$id], $qty[$i]);

Also providing the constructor for Cart model in the question would be a good idea.

  • thanks for your answer.. I've already solved the the problem.. btw i was checking what my Cart model is returning by doing the echo in for loop. i forgot to remove it from the question – Rajin Jun 12 '20 at 12:37
  • Do post how you solved your issue and what exactly the issue was. Would be helpful for others. – user2754876 Jun 13 '20 at 09:54
  • i will keep it mind next time.. btw the problem i was facing, (as mentioned in the question) wherever i was trying to update the cart item's, the total price of the cart item's was not showing accurately... i solved it by removing the cart and create a new cart with updated quantity of cart items. – Rajin Jun 13 '20 at 10:38