Laravel 5 Collections: Adding an Element to the End of a Collection With push

April 22, 2018 —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 push method modifies the collection instance it was invoked on.

#Signature

1public function push(
2 $value
3);

#Example Use

The following code example demonstrates how to use the push method to add an item on the end of a collection:

1use Illuminate\Support\Collection;
2 
3// Create a new collection instance.
4$collection = new Collection([
5 'I am first',
6 'I am second'
7]);
8 
9// Push an item onto the collection.
10$collection->push('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 0 => string 'I am first'
5 1 => string 'I am second'
6 2 => string 'I am third'

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
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.