1

I am not very familiar with php arrays and trying to change value of an array generated from laravel collection with no success. Here is the code :

$items = Purchase::find($id)->items->toArray();
foreach ($items as $i) {
    $i['itemdesc'] = "Test";
}
info($items);

The $items array looks like this :

[2021-06-05 17:29:20] local.INFO: array (
  0 => 
  array (
    'itemcode' => '54',
    'itemdesc' => 'FARROAD 225/40ZR18  FRD26 92W XL',
  ),
  1 => 
  array (
    'itemcode' => '141',
    'itemdesc' => 'TRACKMAX 225/40ZR19 X-PRIVILO TX3 93Y XL',
  ),

The values for itemdesc are not getting changed. If I add info($i) inside the foreach loop I can see that the value is changed. Can someone help what is wrong in above code.

2 Answers2

0

You can try to add a &, that will allow you to loop the array by reference

foreach ($items as & $i) {
//                 ^
//                 |
//                here
aletzo
  • 2,471
  • 1
  • 27
  • 31
0

I think you can use transform using collection.

The transform method iterates over the collection and calls the given callback with each item in the collection. The items in the collection will be replaced by the values returned by the callback:

Side Note

Unlike most other collection methods, transform modifies the collection itself. If you wish to create a new collection instead, use the map method.

$items = Purchase::find($id)->items;
$items->transform(function($item) {
        $item->itemdesc="test";
        return $item;
    });

info($items);

Ref:https://laravel.com/docs/8.x/collections#method-transform

John Lobo
  • 14,355
  • 2
  • 10
  • 20