Laravel 5 Collections: Adding New Elements to a Collection With put

April 22, 2018 —John Koster

The put method is used to add a new item to the collection with a given $key and $value. The put method modifies the original Collection instance and returns a reference to it.

#Signature

1public function put(
2 $key,
3 $value
4);

#Example Use

The following code example highlights the usage of the put method:

1use Illuminate\Support\Collection;
2 
3// Create a new collection instance.
4$collection = new Collection([
5 'first' => 'I am first',
6 'second' => 'I am second'
7]);
8 
9// Put a new item in the collection.
10$collection->put('third', 'I am third');

After the above code has executed, the $collection variable would contain a value similar to the following output:

1object(Illuminate\Support\Collection)
2 protected 'items' =>
3 array
4 'first' => string 'I am first'
5 'second' => string 'I am second'
6 'third' => string 'I am third'

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.