Home > Blockchain >  Adding attributes to laravel collection
Adding attributes to laravel collection

Time:02-16

i have to put some attributes to my laravel collections.

My laravel collection original attributes :

array:2 [▼
    0 => array:20 [▼
        "curr" => "IDR"
        "price" => 5500000.0
        "rate" => 14325.803
        "qty" => 2
    ]
    1 => array:20 [▼
        "curr" => "IDR"
        "price" => 1500000.0
        "rate" => 14325.803
        "qty" => 1
    ]
]

i want to add "amount" attribute which the result of multiplying "price" x "qty" like so :

array:2 [▼
    0 => array:20 [▼
        "curr" => "IDR"
        "price" => 5500000.0
        "rate" => 14325.803
        "qty" => 2
        "amount" => 11000000.0
    ]
    1 => array:20 [▼
        "curr" => "IDR"
        "price" => 1500000.0
        "rate" => 14325.803
        "qty" => 1
        "amount" => 1500000.0
    ]
]

i tried to do it by put() method of laravel collection, but it seems the each() method will remove the collection instance, so i can't use the put() method :

$collection->each(function($item) {
    $item->put('amount', $item->price * $item->qty);
});

What's the solution of this ?

CodePudding user response:

You can't use ->put in an ->each loop for this case, because ->each does not loop the items by reference. So all modifications to the item are lost after the loop.

You can map the array to return your actual $item merged with the extra key amount. The correct method to use is ->map.

$collection = $collection->map(function($item) {
    return array_merge($item, [
        'amount' => $item->price * $item->qty;
    ]);
});

https://laravel.com/docs/9.x/collections#method-map

  • Related