Laravel 5 Collections: Adding New Elements to a Collection With put

Laravel 5 Collections: Adding New Elements to a Collection With put

Laravel 5

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.

Signature

public function put(
    $key,
    $value
);

Example Use

The following code example highlights the usage of the put method:

use Illuminate\Support\Collection;

// Create a new collection instance.
$collection = new Collection([
    'first'  => 'I am first',
    'second' => 'I am second'
]);

// Put a new item in the collection.
$collection->put('third', 'I am third');

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
      'first'  => string 'I am first' 
      'second' => string 'I am second'
      'third'  => string 'I am third' 

Start the Discussion

Leave a comment

Subscribe to our newsletter