George
George

Reputation: 69

How to put value on laravel collection?

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
    ]
  ]
}

Upvotes: 4

Views: 6647

Answers (3)

wesamly
wesamly

Reputation: 1584

You can use transform method to update the collection item as following:

$collection = collect([
    [
        'id' => 83,
        'status' => 'offline',
        'created_date' => 'Oct 31, 2018'
    ]
]);

$collection->transform(function($entry, $key) {
    if ($key == 0) {
       $entry['foo'] = 1;
    }
    return $entry;
});

Upvotes: 0

kmuenkel
kmuenkel

Reputation: 2789

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);

Upvotes: 3

Shailendra Gupta
Shailendra Gupta

Reputation: 1118

use this

$data = Model::all();
$data[0]->foo = 'your data here';

Upvotes: 2

Related Questions