Search

Laravel Collection Public API: flatMap

November 29, 2016 —John Koster

flatMap(callable $callback)

The flatMap method is used in the same way as the map (discussed in the Laravel Collection Public API: map article) method but will collapse the resulting collection. The following two code examples are equivalent:

1<?php
2 
3use Illuminate\Support\Collection;
4 
5// Create a new collection instance.
6$collection = new Collection([
7 'first', 'second', 'third'
8]);
9 
10// Create a new collection where all the strings
11// in the original collection have had their case
12// changed to upper-case.
13$newCollection = $collection->map(function($item, $key) {
14 return strtoupper($item);
15})->collapse();
16 
17 
18// Using the flatMap method
19$newCollection = $collection->flatMap(function($item, $key) {
20 return strtoupper($item);
21});

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.