How to put value on first element in laravel collection ? Something like that $collection->put('foo', 1)
but adding value to the first element.
Collection {#376
#items: array:1 [
0 => array:9 [
"id" => 83
"status" => "offline"
"created_date" => "Oct 31, 2018"
// add foo => 1 here
]
]
}
I suspect there's a cleaner way to do this, but this is the best I could come up with at the moment. You could also use map
or transform
with a comparison run on the key value that gets sent to their closures, but that would end up cycling through all elements of the array despite you knowing the specific one you want to target.
$collection = collect([
[
'id' => 83,
'status' => 'offline',
'created_date' => 'Oct 31, 2018'
]
]);
$firstKey = $collection->keys()->first(); //This avoids the unreliable assumption that your index is necessarily numeric.
$firstElement = $collection->first();
$modifiedElement = array_merge($firstElement, ['foo1' => 1]);
$collection->put($firstKey, $modifiedElement);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With