Laravel Collection Public API: prepend

November 30, 2016 —John Koster

prepend($value, $key = null)

The prepend method will add an a given $value to the beginning of the collection. You can also supply an optional $key that will be used as the key for the new $value when adding an item to the beginning of an associative array. The prepend method returns a reference to the original collection instance.

The following code example demonstrates the usage of the prepend method:

1<?php
2 
3use Illuminate\Support\Collection;
4 
5// Create a new collection instance.
6$collection = new Collection([
7 'XS', 'S', 'M', 'L', 'XL'
8]);
9 
10// Add a new item to the beginning of the collection.
11$collection->prepend('Select a shirt size');

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=6)
4 0 => string 'Select a shirt size' (length=19)
5 1 => string 'XS' (length=2)
6 2 => string 'S' (length=1)
7 3 => string 'M' (length=1)
8 4 => string 'L' (length=1)
9 5 => string 'XL' (length=2)

The following examples demonstrate the usage of the prepend method when supplying an argument for the $key parameter:

1<?php
2 
3// Create a new collection to work with.
4$collection = collect([
5 'name' => 'Holiday Jumper',
6 'color' => 'Red'
7]);
8 
9// Add a new item to the beginning of the collection.
10$collection->prepend('XL', 'size');

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

1Collection {
2 #items: array:3 [
3 "size" => "XL"
4 "name" => "Holiday Jumper"
5 "color" => "Red"
6 ]
7}

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.