Laravel Collection Public API: put

November 30, 2016 —John Koster

put($key, $value)

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.

The following code example will highlight the usage of the put method:

1<?php
2 
3use Illuminate\Support\Collection;
4 
5// Create a new collection instance.
6$collection = new Collection([
7 'first' => 'I am first',
8 'second' => 'I am second'
9]);
10 
11// Put a new item in the collection.
12$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)[133]
2 protected 'items' =>
3 array (size=3)
4 'first' => string 'I am first' (length=10)
5 'second' => string 'I am second' (length=11)
6 'third' => string 'I am third' (length=10)

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.