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- Laravel Collections – Introduction to Collections
- Laravel Collections – make Method
- Laravel Collections – wrap() and unwrap() Methods
- Laravel Collections – map() Method
- Laravel Collections – times() Method
- Laravel Collections – collapse() Method
- Laravel Collections – contains() & containsStrict() Methods
- Laravel Collections – each() Method
- Laravel Collection – Using toJson() Method
- Laravel Collection – Filtering Collection Items using where()
- 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.