How to update a value in the bank, subtracting or adding the old amount

Viewed 22

I'm developing an API for a warehouse system, and in the update method I need to update the amount of my stock/inventory (example, the entrance has 4 meters of wood, in the edit I changed it to 3 meters, so I remove 4 meters from the inventory which would be the previous value, and then I add the 3 meters of the edit), I'm having trouble on how to get this data that was inserted when my entry in the inventory was created, a part of my code:

public function update(EntradaUpdateFormRequest $request, $id)
{
    $entrada = Entrada::findOrFail($id);
    //there's a lot of code in this part...
    //and below is the logic of moving the inventory table...
    // logic to update or add quantity of items in inventory
                $inventario = Inventario::where('departamento_id','=',$entrada->departamento_id)
                                        ->where('local_id','=',$entrada->local_id)
                                        ->where('item_id','=',$entrada_items["item_id"])
                                        ->first();

                if ($inventario) {
                    $inventario->quantidade - //this is the biggest obstacle, I think the scheme would be to subtract the previous total, and then add the new total, but as
                    //do to change the value that was added when this record was created in the store method.
                    $inventario->quantidade += $entrada_items["quantidade"];
                    $inventario->save();
                } else {
                    $inventario = new Inventario();
                    $inventario->departamento_id = $entrada->departamento_id;
                    $inventario->item_id = $entrada_items["item_id"];
                    $inventario->local_id = $entrada->local_id;
                    $inventario->quantidade = $entrada_items["quantidade"];
                    $inventario->qtd_alerta = 0;
                    $inventario->save();
                }
1 Answers

why dont you just affect the quantity directly

if ($inventario) {
    $inventario->quantidade = $entrada_items["quantidade"];
    $inventario->save();
} else {
Related