Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.4: how to iterate through request array?

My request data represents an array of new and existing items. I'm trying to through this array to update and create items.

This is how I retrieve the array:

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

Later in the code I update an existing item:

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

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

How can I loop through request data in Laravel ?

This is the whole code as I run it (want to get rid of 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 an input from html (just to show I checked the form also, the data comes just fine):

<input id="basicItemNumber-31" class="form-control" name="items[31][number]" placeholder="Unique number" value="31" type="text">
like image 713
sr9yar Avatar asked Feb 16 '17 11:02

sr9yar


1 Answers

It's likely that somewhere inside your for you've inadvertently changed the value of your underling $item as you pass it by reference (using the & before the variable name.)

It's considered bad practice by some or most people as it can lead to "unexpected" behaviour, For example. take the sample code below that loops through an array of $items twice once by reference and once by value.

<?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"
}
like image 150
Luke Avatar answered Oct 19 '22 10:10

Luke