I am making laravel shopping cart and now working with laravel session.
My imagine is:
- If cart session is null:
Adding first product - If not:
Check request product's ID, if it is not existing product's ID:
-> push to cart session array
If not:
-> don't push to cart session array
I can push product in to session but with the first product, when I add one more time the same product, it was added, but the 2nd, 3rd...product work fine.
I try many time but not found the way to solve. Can you help me?
This is my CartController with add method*
public function add(Request $request)
{
$cartItems = session('cart');
$productInfoToCart = array(
"id" => request('id'),
"name" => request('name'),
"code" => request('code'),
"price" => request('price')
);
if ($cartItems !== null){
if (array_search(request('id'), array_column($cartItems, 'id'))) {
return redirect ('/cart')->with('status', 'Product exists, you can change quantity before payment');
} else {
$request->session()->push('cart', $productInfoToCart);
$request->session()->flash('status', 'Product added to cart');
return redirect('/cart');
}
} else {
$request->session()->push('cart', $productInfoToCart);
$request->session()->flash('status', 'First Product added to cart');
return redirect('/cart');
}
}