Update product count in MYSQL using Eloquent

I am creating a simple ecommerce application using php using Laravel Rloquent ORM. I have a cart class that creates an object with 3 properties, items, total and total price. Items are grabbed from the product table in MySQL. This is how the cart object is created when I print it to the browser console using 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, after successfully checking / ordering the item (s) in the cart, I need to update / reduce the number of those items back in my product table in my database by the quantity specified in each item in the cart object. I'm in this state.

UPDATE . This is the new logic I tried 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          

}

      

This logic now works in terms of getting the corresponding products back into my DB and decrementing, however, if there is more than one item in the cart object, all items are decremented by the last number of items and not by the associative item quantity. This line is here:

$product->decrement('quantity', $item['qty']); // here is the issue

      

Decreases each product by the last ['qty'] element, not the ['qty'] element of the element this product was associated with ... Any suggestions?

+3


source to share


2 answers


What, instead of getting your collection of products from item IDs, iterate over the items, find the product with that item ID, and decrease the quantity.

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

      



Think that only the bad part of this method is doing the query multiple times for each item to find the product. Not sure what the overhead might be causing.

+1


source


You looped over each $ item above, and so $ item is now set as the last $ items entry. When you iterate over $ products, you are not iterating over $ items again, so you only use the last $ item above.



0


source







All Articles