3
votes

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?

2

2 Answers

2
votes

What about instead of getting your collection of products from the item ids, loop over the items, find the product with that item id, and decrement the qty.

foreach ($items as $item) {
    $product = Product::find($item['id']);
    $product->decrement('quantity', $item['qty']);
}

Think the only bad part of this is running the query multiple times over each item to find the product. Not sure the overhead that will cause.

0
votes

You looped through each $item above, and so $item is now set as the last record of $items. When you are looping through $products, you aren't looping through $items again, so it is only using the last $item that was set above.