Linked Questions

Popular Questions

Laravel map(): How to alter objects and arrays?

Asked by At

I have a multidimensional collection. I want to iterate it and alter some of its child objects and arrays using the map() function: https://laravel.com/docs/5.1/collections#method-map

Sample content:

[
    {
        'address': 'Somestreet 99'
        'orders': [
            {'id': 11},
            {'id': 67}
        ]
    }
]

Example

  $deliveries = $delivery_addresses->map(function($delivery_address){
     $orders = $delivery_address->orders->filter(function($order){
        return $order->id == 67;
     });

     $delivery_address['address'] = 'A different street 44'
     $delivery_address['orders'] = $orders;
     $delivery_address['a_new_attribute'] = 'Some data...';

     return $delivery_address;
  });

Expected result:

[
    {
        'address': 'A different street 44'
        'orders': [
            {'id': 67}
        ],
        'a_new_attribute': 'Some data...;
    }
]

The result is that only string type variables will be changed. Any arrays or objects will stay the same. Why is this and how to get around it? Thanks! =)

Related Questions