0

I'm a beginner in laravel, I would like to update multiple rows using one input field.

My Database records:

enterage description here

For an instance, my input field has the value of 500, When I submit this field, it will then Update the multiple selected id from database from oldest to latest.

If the first row has the quantity of 100 it will be 500 - 100, and then it will proceed to the second row in which the value of input field is now 400 and it will again get the difference of the second row 400 - 200 until the input field becomes 0.

Is this possible? Thank you.

Lakhwinder Singh
  • 5,536
  • 5
  • 27
  • 52
Theonly
  • 59
  • 5
  • 3
    Post your code that you've tried, before that read this first : https://stackoverflow.com/help/how-to-ask – Sethu Jun 21 '19 at 06:43
  • My solution will be like this: loads all of the needed records and then do the calculation and do an update for all of them. Check out for a massive update here: https://stackoverflow.com/questions/22430716/eloquent-model-mass-update – Felix Jun 21 '19 at 07:03
  • Ok I understand you want to keep updating each row until you "deplete" your input but **how** are you going to be updating the rows? Will you be setting quanitty requested to 0? – apokryfos Jun 21 '19 at 08:19

1 Answers1

0

Run foreach and pass your input field inside it. Simple

You can follow below code for understanding ..

public function updateRecord(Request $req)
    {
        //get data from oldest(ASC) to latest (desc).
        $var = $req->input_field;
        $data = ModelName::orderBy('id','asc')->get();

        foreach ($data as $key)
        {
            // ($var < 0) in case negative value
            if($var == 0 || $var < 0)
            {
                break;
            }       
            //find row with id
            $singleRow = ModelName::find($key->id);
            //holding data base quantity
            $dummyHolder = $single->quantity_requested;
            $single->quantity_requested = $dummyHolder + $var;
            $singleRow->save();

            //update variable
            $var = $var - $dummyHolder;
        }
    }
Karan Sadana
  • 1,363
  • 7
  • 11
  • Thank you sir!, I will try this one. – Theonly Jun 21 '19 at 09:28
  • Hi sir I ask another question connected to this question. https://stackoverflow.com/questions/56720477/how-to-loop-input-field-value-and-insert-to-its-row-based-on-the-database-value – Theonly Jun 23 '19 at 02:14