sr9yar
sr9yar

Reputation: 5310

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">

Upvotes: 7

Views: 25159

Answers (2)

Spholt
Spholt

Reputation: 4012

Try something like this as it will keep your scope local:

$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();
        }
    }
});

Upvotes: 0

Luke
Luke

Reputation: 3541

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"
}

Upvotes: 2

Related Questions