Laravel Collections – map() Method

laravel collection map

This post is part of the series Laravel Collection

Other posts in this series:

  1. Laravel Collections – Introduction to Collections
  2. Laravel Collections – make Method
  3. Laravel Collections – wrap() and unwrap() Methods

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.

Example of Laravel Collection Map

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

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

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