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

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


collect($deliver_addresses)->map(function ($address) use ($input) {    $address['id']              = $input['id'];    $address['a_new_attribute'] = $input['a_new_attribute'];    return $address;});


Addressing your recent edits, try this:

$deliveries = $deliver_addresses->map(function($da) {    $orders = $da->orders->filter(function($order) {        return $order->id == 67;    });    $da->unused_attribute = $orders->all();    return $da;});

What the case most likely is here is that you are correctly overwriting that attribute. Then when you are attempting to access it Laravel is querying the orders() relationship and undoing your changes. As far as Laravel is concerned these are the same:

$delivery_address->orders;$delivery_address['orders'];

This is why the changes are only working on objects. If you want to save that permanently then actually save it, if not use a temporary attribute to contain that data.


$paymentMethods = $user->paymentMethods()->map(function($paymentMethod){            return $paymentMethod->asStripePaymentMethod();        });