Laravel Map() : Laravel Collection Method with Example

By Parth Patel on Oct 05, 2020

Laravel map() is a Laravel Collections method to pass callback function to each item in Collection. It is a easy yet powerful method to manipulate data in Laravel Collection. After operating on each item, map() method returns new Collection object with updated items.

Note: The map() method will not modify the original Laravel Collection, so it is safe to use without worrying about unknown data mutation.

The Callback function requires two parameters - $item, $key in this order. Obviously these are just variables to hold parameter value, so you can use any name.

Definition

Here is the actual definition of map() method defined in Illuminate\Support\Collection class. This is just for understanding, you won't have to worry about this.

/**
 * 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));
}

Laravel map() Example with Generic Collection

Here's the simple example:

$names = collect(["john","dave","michael"]);

//let's try changing first letter to uppercase in all names

$ucnames = $names->map(function($name, $key) {
	return ucwords($name);
});

$ucnames->all();

// ["John","Dave","Michael"]

Laravel map() Example with Eloquent Collection

map() method is often used to manipulate data fetched from Eloquent queries. So, let's review one such example:

$users = User::all();

$mappedcollection = $users->map(function($user, $key) {									
	return [
			'id' => $user->id,
			'name' => $user->name
		];
	});

//output

[
	[
		"id" => 1,
		"name" => "John Admin"
	],
	[
		"id" => 2,
		"name" => "John Doe"
	]
]

map() method is a very powerful Laravel Collection method and when combined with other methods like join() can perform complex operations for you very easily.