Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

yonis's avatar
Level 2

updating multible rows values by adding them and subtracting one value and storing the remaining values in the rows using laravel

I have three tables which are joined: Item, Inventory and Used Inventory. items _table Inventories_table and used_inventories table , I want to update Quantity of Inventory when used_inventory is added. because used inventory and inventory are both connected to Item table. so the problem is when I try to update the quantity in Inventory Table by getting the Item id, I have to sum all the quantities of Item and then subtract the Used Quantity and update the rest in the Quantity of Inventory.

I want to store quantity of items in the inventory table. when this quantity is used, I want to subtract that quantity from the used quantity and store it in the used_inventory table. So when subtracting used_inventory quantity quantity from inventory quantity,I have to update it,So the item may have many inventory Quantities, For example Item 'Y' may have quantity of '10', again it may have '20' in the inventory table,So if used_quantity of Item 'Y' is equal to '15', I have to subtract it from the Accregate of '10+20',because the item has both these quantites. and as you can understand, these two values are stored in different rows. so the problem is when I try to update the rows it will update all, I mean both '10'and '15' will be subtract '20'. but what I want is to Sum and the subtract and update for example (10+15)-20 = 5, so the item will have 5 quantities in one of the rows.

public function store(Request $request) { $request->validate([ 'item_id'=>'required', 'project_id'=>'required', 'quantity'=>'required', ]);

$used_inventories = new UsedInventory();
$used_inventories->item_id = $request->item_id;
$used_inventories->project_id = $request->project_id;
$used_inventories->quantity = $request->quantity;
$used_inventories->reference = $request->reference;
$used_inventories->description = $request->description;

$item = Item::where('id','=',$request->item_id)->get();
$used_quantity = $request->quantity;
foreach ($item as $i){
    $updated_quantities = $i->inventories->pluck('quantity')->sum();

    $quantity_now = $updated_quantities - $used_quantity;

    if ($used_quantity > $updated_quantities)
    {
        return back()->with('warning','This Quantity is not available');
    }
    $inventory_update = DB::table('inventories')
        ->where('item_id',$request->item_id)
        ->update(['quantity'=>$quantity_now]);
    $used_inventories->save();
}

return back()->with('save_success','Used Inventory');

}

0 likes
0 replies

Please or to participate in this conversation.