Laravel

Laravel Collections – map() Method

In this post, we will look at how we can use the map() method to perform some action on each element of Laravel Collections.

3 April 20192 min read245 words
Laravel Collections – map() Method

In this post, we will look at how we can use map() method to perform some action on each element of Laravel Collections.

The map method applies a given callback function to each element of a collection. The callback function will modify the item and create a new Laravel collection for them.

The map method will not modify the original collection, instead it will return a new collection with all the changes. The provied callback function should accept the $item and the items $key as it's only argument.

Signature

Below is the signature of the map() in Illuminate\Support\Collection class.

php
/**
 * Run a map over each of the items.
 *
 * @param  callable  $callback
 * @return static
 */
public function map(callable $callback)
{
    $keys = array_keys($this->items);

    $items = array_map($callback, $this->items, $keys);

    return new static(array_combine($keys, $items));
}

Example

For the following example, we will transform each item in the collection and return a new collection.

php
use Illuminate\Support\Collection;
// Create a new collection

$collection = new Collection([
    'jhon', 'tom', 'mike', 'stuart'
]);

// Change all items to uppercase and create a new collection of them
$names = $collection->map(function($item, $key) {
   return strtoupper($item);
});

The $names variable will be an instance of Collection class and contain a value similar to following:

php
Collection {#510 ▼
  #items: array:4 [▼
    0 => "JHON"
    1 => "TOM"
    2 => "MIKE"
    3 => "STUART"
  ]
}

If you dump the original collection $collection, you will find it will remain unchanged.