You could use a package like Crinsane/LaravelShoppingcart that could handle that for you automatically.
Apr 9, 2015
3
Level 6
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.
Please or to participate in this conversation.