0

I am using Angular2 for my frontend and laravel for my back end. I am trying to parse an array and store all of it into different rows but currently only the last record being recieved is being saved to the database.

public function SaveOrder(Request $request) {
  $input = $request->all();
  $order = new Order;

  foreach ($input as $arr) {
      foreach ($arr as $key => $value) {
         if (array_key_exists($key, $arr) && !empty($value)) {
              $order->$key = $value;
         }
      }
  }
  $order->save(); 
}

enter image description here

$input = $request->all();
foreach ($input as $arr) {
    var_dump($arr);
    foreach ($arr as $key => $value) {
        if (array_key_exists($key, $arr) && !empty($value)) {
        }
    }
}

var_dump of the array

enter image description here

ghan
  • 525
  • 11
  • 24

2 Answers2

1

If you take a closer look, you'll notice your SaveOrder method loops through the given collection, sets the $order->$key = $value for productName and productDesc - and in the next iteration overwrites these values. That's why, when you save() the Order model, all you're inserting is the last (iterated) pair of values.

What you should do is to build an array of arrays, containing all "rows" to insert, and then perform a bulk insert.

lesssugar
  • 15,486
  • 18
  • 65
  • 115
0

Thanks @lesssugar I figured it out although I am having second thoughts of doing it this way since it seems inefficient

public function saveOrder(Request $request) {

    $input = $request->all();
    foreach ($input as $arr) {
        foreach ($arr as $key => $value) {
            if (array_key_exists($key, $arr) && !empty($value)) {
                $data = array($arr);
            }
        }
        DB::table('test')->insert($data);
    }
}
ghan
  • 525
  • 11
  • 24
  • Yes, it is inefficient. Your bulk insert should be *outside* of the 2 loops. In the loops, you should only build the insert data array, not perform the database query. – lesssugar Jun 22 '17 at 20:37
  • @lesssugar If I move it outside of the first foreach I have the same problem as before where it only saves the last record – ghan Jun 22 '17 at 20:53