Laravel 5.4: how to iterate over an array of requests?

My query data is an array of new and existing elements. I am trying to update and create elements through this array.

This is how I retrieve the array:

$userInput = $request->all();
foreach( $userInput['items'] as $key=>&$item){

Later in the code, I update the existing element:

$updateItem = Item::find($item['id']);
$updateItem->number = $item['number'];
$updateItem->save();

But $item['number']it seems to contain the old input from previous updates, and not the value that I last entered.

How can I program the request data in Laravel?

This is all the code when I run it (I want to get rid of the confusion):

$userInput = $request->all();
// checking $userInput here
// I can see the new value in the array

foreach( $userInput['items'] as $key=>$item){
  if($item['delete'] == 1) {
    Item::where('order_id',$order->id)
      ->where('id',$item['id'])
      ->delete();
  } else {
    if(empty($item['id'])) {
    } else {
      $updateItem = Item::find($item['id']);
      $updateItem->number = $item['id'];
      $updateItem->save();
    }
  }
}

This is a tab from html (just to show that I also checked the form, the data is just fine):

<input id="basicItemNumber-31" class="form-control" name="items[31][number]" placeholder="Unique number" value="31" type="text">
+4
source share
2 answers

, - for underling $item ( & .)

, "" , . , array of $items .

<?php

$items = ['one','two','three'];

foreach ($items as &$item) {
    //do nothing.
}

foreach ($items as $item) {
    //do nothing again.
}

var_dump($items);

//outputs

array(3) {
  [0]=>
  string(3) "one"
  [1]=>
  string(3) "two"
  [2]=>
  &string(3) "two"
}
+1

- , :

$request['items']->each(function($item, $key) use ($order) {
    if ($item->delete) {
        Item::where('order_id',$order->id)
              ->where('id',$item['id'])
              ->delete();
    } else {
        if (!empty($item['id'])) {
            $updateItem = Item::find($item['id']);
            $updateItem->number = $item['id'];
            $updateItem->save();
        }
    }
});
0

Source: https://habr.com/ru/post/1669919/


All Articles