in my shopping cart app i'm building customers carts using addToCart method, the method checks if the cart is empty or if product already exist in the cart, and if the newly added product ID exist in the cart i'm only adding the qty to existing product in the cart.
public function store($id)
{
$product = Product::find($id);
if(!$product) {
abort(404);
}
$cart = session()->get('cart');
// if cart is empty then this the first product
if(!$cart) {
$cart = [
$id => [
"name" => $product->name,
"qty" => $request->quantity,
"price"=>$product->price,
"color" => $request->color,
"size" => $request->size,
"image" => $product->poster,
]
];
session()->put('cart', $cart);
return redirect()->back()->with('success', 'Product added to cart successfully!');
}
// if cart not empty then check if this product exist then increment quantity
if(isset($cart[$id])){
$cart[$id]['qty'] = $request->quantity;
session()->put('cart', $cart);
return redirect()->back()->with('success', 'Product added to cart successfully!');
}
// if item not exist in cart then add to cart with quantity
$cart[$id] = [
"name" => $product->name,
"qty" => $request->quantity,
"price"=>$product->price,
"color" => $request->color,
"size" => $request->size,
"image" => $product->poster,
];
session()->put('cart', $cart);
return redirect()->back()->with('success', 'Product added to cart successfully!');
}
I'm updating the the app product so every product has multiple options (size, Color and qty), so basically a user can add the same product to the cart multiple times as not and it has deferent option (size, color, qty).
a good example for this will be a shirt? a customer can add same shirt multiple times in the cart as long as the (size or colors ) are deferent
any idea on how to achive this type of cart.