I have a list of records where I want to update the quantities with new values, but when I use the update or Create method, it only updates only one record.
$data = DB::table('inventory_items')->select('inventory_items.*')
->join('sorder_parts', 'inventory_items.id', 'sorder_parts.inventory_id')
->where('sorder_parts.sorder_id', '=', $id)
->selectraw('inventory_items.quantity - sorder_parts.quantity AS new_quantity')
->get();
foreach ($data as $product_item) {
$reduce_quantity = InventoryItem::updateOrCreate(['id' => $product_item->id],
['quantity' => $product_item->new_quantity]);
dd($data, $reduce_quantity);
}
There’s no need to upsert when you know the records exist in that table, as you’re looping through the set you queried. Set and update the property instead:
foreach ($data as $product_item) {
$product_item->quantity = $product_item->new_quantity;
$product_item->save();
}
Also, make sure the properties you’re attempting to populate are defined in the fillable array in your InventoryItem model (if you haven’t defined a $guarded property).