MehulBawadia's avatar

Update the value if same key of array or insert as new value

I am making an eCommerce web application and I am a newbie.

What I am trying to achieve is when a product exists in the session, I want to update the quantity of that product when Add to Cart button is clicked. And if it doesn't exists in the session, I want to insert it in the session.

Code that I have tried so far

public function store( $id ) {

        $product = Product::findOrFail( $id );

    if ( \Session::has( 'cart' ) && is_array( \Session::get('cart') ) ) {
        \Session::push('cart', ['product' => (int)$id, 'quantity' => 1 ]);
    } else {
        \Session::put('cart', ['product' => (int)$id, 'quantity' => 1 ]);
    }

    \Session::flash('added_product', 'Product Added in the cart');

    return \Redirect::back();
}

The output that I get for the above code is:

array:3 [▼
  0 => array:2 [▼
    "product" => 1
    "quantity" => 1
  ]
  1 => array:2 [▼
    "product" => 2
    "quantity" => 1
  ]
  2 => array:2 [▼
    "product" => 1
    "quantity" => 1
  ]
]

The "product" is the id of the product.

For 1 product, it is working fine, but when I try to add the same product, it gets appended.

How do I resolve this ? Kindly help me out.

0 likes
3 replies
MehulBawadia's avatar

@foxted I know I can have a package like you just mentioned, but I want to learn and then move to pre-built packages.

foxted's avatar

Take a look at the addRow function in this case, it should give you a hint.

Please or to participate in this conversation.