添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
侠义非凡的炒饭  ·  spring websocket ...·  4 月前    · 
文武双全的单车  ·  org.apache.pdfbox:pdfb ...·  7 月前    · 
低调的炒面  ·  Starting and running ...·  8 月前    · 

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"