Laravel Collections – map() Method

Laravel Collections – map() Method

Laravel Collections ( 11 Lessons )

Laravel Collections is one of the most powerful features of Laravel. Basically, collections are PHP arrays but it’s an Object Oriented approach to deal with PHP arrays.

see full series
  1. Laravel Collections – Introduction to Collections
  2. Laravel Collections – make Method
  3. Laravel Collections – wrap() and unwrap() Methods
  4. Laravel Collections – map() Method
  5. Laravel Collections – times() Method
  6. Laravel Collections – collapse() Method
  7. Laravel Collections – contains() & containsStrict() Methods
  8. Laravel Collections – each() Method
  9. Laravel Collection – Using toJson() Method
  10. Laravel Collection – Filtering Collection Items using where()
  11. Laravel Collection – Using splice() Method to Remove Items

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.

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

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:

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.

Your little help will keep this site alive and help us to produce quality content for you.