I am building a small e-commerce site out and want to be able to have the stock on hand be updated when items are added or deleted from someone's cart. In my cart controller, I have four functions: one to add an item, one to increase the item, one to decrease the item, and one to remove an item. Here is the code for that:
public function addItemToCart(Request $request, $id) {
$prevCart = $request->session()->get('cart');
$cart = new Cart($prevCart);
$product = Product::find($id);
$cart->addItem($id, $product);
$request->session()->put('cart', $cart);
return redirect()->route("home");
}
public function increaseSingleProduct(Request $request, $id) {
$prevCart = $request->session()->get('cart');
$cart = new Cart($prevCart);
$product = Product::find($id);
$cart->addItem($id, $product);
$request->session()->put('cart', $cart);
return redirect()->back();
}
public function decreaseSingleProduct(Request $request, $id) {
$prevCart = $request->session()->get('cart');
$cart = new Cart($prevCart);
if( $cart->items[$id]['quantity'] > 1) {
$product = Product::find($id);
$cart->items[$id]['quantity'] = $cart->items[$id]['quantity']-1;
$cart->items[$id]['totalSinglePrice'] = $cart->items[$id]['quantity'] * $product['price'];
$cart->updatePriceAndQunatity();
$request->session()->put('cart', $cart);
}
return redirect()->back();
}
public function deleteItemFromCart(Request $request, $id) {
$cart = Session::get('cart');
if(array_key_exists($id, $cart->items)){
unset($cart->items[$id]);
}
$prevCart = $request->session()->get("cart");
$updatedCart = new Cart($prevCart);
$updatedCart->updatePriceAndQunatity();
$request->session()->put("cart",$updatedCart);
return redirect()->route('shopping cart');
}
The quantity here does not refer to the quantity on hand, it refers to the quantity in the cart. In the products table, I have a column that is called stock_quantity. Ideally, this is what I would like to get updated as each function is performed.
I may not be getting the complexity of your question. Don't you just have to find the product and increment or decrement?
$product = Product::findOrFail($item_id);
$product->stock_quantity++; // or --
$product->save();
I wouldn't be doing this as you add to the cart though. I'd do it on checkout instead so that you don't leave your stock committed with an abandoned cart. Alternatively, if you really need to commit your stock while someone has something in the cart, implement a function to remove the committed stock if it's abandoned.