Laravel 5 Collections: Adding an Element to the Beginning of a Collection With prepend

Laravel 5 Collections: Adding an Element to the Beginning of a Collection With prepend

Laravel 5

The prepend method will add a 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.

Signature

public function prepend(
    $value,
    $key = null
);

Example Use

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

use Illuminate\Support\Collection;

// Create a new collection instance.
$collection = new Collection([
    'XS', 'S', 'M', 'L', 'XL'
]);

// Add a new item to the beginning of the collection.
$collection->prepend('Select a shirt size');

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

object(Illuminate\Support\Collection)
  protected 'items' => 
    array
      0 => string 'Select a shirt size'
      1 => string 'XS'
      2 => string 'S' 
      3 => string 'M' 
      4 => string 'L' 
      5 => string 'XL'

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

// Create a new collection to work with.
$collection = collect([
    'name'  => 'Holiday Jumper',
    'color' => 'Red'
]);

// Add a new item to the beginning of the collection.
$collection->prepend('XL', 'size');

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

Collection {
  #items: array [
    "size"  => "XL"
    "name"  => "Holiday Jumper"
    "color" => "Red"
  ]
}

Start the Discussion

Leave a comment

Subscribe to our newsletter