Laravel Collection Public API: push

November 30, 2016 —John Koster


The push method is the logical opposite of the prepend method and will push an item onto the end of the collection. The push method returns a reference to the original collection instance.

The following code example shows how to use the push method to put an item on the end of the collection:

3use Illuminate\Support\Collection;
5// Create a new collection instance.
6$collection = new Collection([
7 'I am first',
8 'I am second'
11// Push an item onto the collection.
12$collection->push('I am third');

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

2 protected 'items' =>
3 array (size=3)
4 0 => string 'I am first' (length=10)
5 1 => string 'I am second' (length=11)
6 2 => string 'I am third' (length=10)

It should be noted that the push method cannot be used to set the key of the item that is being added to the collection.

Some absolutely amazing

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.