I'm creating a simple ecommerce app using php, utilizing Laravel's Eloquent ORM. I have a cart class that creates an object with three properties, the items, total quantity, and total price. The items are grabbed from a products table in MySQL. This is how the cart object is constructed when I print it out in my browser console via ajax:
{
"items": {
"1": {
"qty": "3",
"price": 1200,
"item": {
"id": 1,
"title": "Tennis Shoes",
"img": "https://s3.amazonaws.com/mybucket/tennis.jpg",
"quantity": 40,
"description": "nice tennis shoes to wear or play in.",
"price": 400
}
}
},
"totalQty": 3,
"totalPrice": 1200
}
Now upon a successful checkout/order of an item(s) in the cart, i then need to update/decrease the quantity of these items back in my products table in my database by the quantity ordered of each item in the cart object. I'm at a standstill with this.
UPDATE This is the new logic i have attempted to use:
try {
$cart = new Cart(); // holds the cart object
$items = $cart->items;
$ids = [];
// after payment is successfully captured and a new order was stored in database
foreach ($items as $item) {
$ids[] = $item['item']['id'];
}
// uses my product model
$products = Product::find($ids);
foreach ($products as $product) {
$product->decrement('quantity', $item['qty']); // here is the issue
}
} catch (Exception $e) {
// catch errors
}
Now this logic works in terms of getting the appropriate products back in my DB and decrementing however, if there is more than one item in the cart object, all products are being decremented by the last item quantity and the not the associative item's quantity. This line here:
$product->decrement('quantity', $item['qty']); // here is the issue
Is decrementing each product by the last item['qty'], rather than the item['qty'] of the item that this product was associated with.... Any suggestions?