How Laravel collection flatMap() works?
- User
How Laravel collection flatMap() works?
- Assistant
The
flatMap()method in Laravel Collections is a powerful way to transform and flatten a collection in one step. It's very useful when you're dealing with nested arrays or collections and want to "flatten" them into a single-level collection.
📌 Basic Explanation:
flatMap()applies a callback to each item in the collection, and then flattens the result into a single-level collection.- If your callback returns an array,
flatMap()will merge all those arrays into a flat collection. - If your callback returns a non-array value, it will just keep that value as-is.
✅ Syntax:
$collection->flatMap(function ($item) { return [ ... ]; // Should usually return an array });
🔍 Example 1: Flattening Nested Arrays
$collection = collect([ ['name' => 'iPhone', 'tags' => ['electronics', 'gadget']], ['name' => 'MacBook', 'tags' => ['electronics', 'laptop']], ]); $flattened = $collection->flatMap(function ($item) { return $item['tags']; }); // Result: // ["electronics", "gadget", "electronics", "laptop"]Here,
flatMap()flattens all thetagsarrays into a single-level collection.
🔄 Difference Between
map()andflatMap()Let's compare with
map()to see the difference:$collection = collect([ ['name' => 'iPhone', 'tags' => ['electronics', 'gadget']], ['name' => 'MacBook', 'tags' => ['electronics', 'laptop']], ]); $result = $collection->map(function ($item) { return $item['tags']; });Result from
map():[ ['electronics', 'gadget'], ['electronics', 'laptop'] ]This gives a nested collection/array of tags.
But with
flatMap():$result = $collection->flatMap(function ($item) { return $item['tags']; });Result from
flatMap():['electronics', 'gadget', 'electronics', 'laptop']It's now a flat collection.
🧠 When to Use
flatMap()Use
flatMap()when you want to:- Transform items into arrays and merge them together.
- Flatten nested collections/arrays.
- Extract multiple values per item into a single list.
🛠️ Real-World Example: Unique Tags
You can chain
unique()afterflatMap()to get unique tags:$uniqueTags = $collection->flatMap(function ($item) { return $item['tags']; })->unique(); // Result: ["electronics", "gadget", "laptop"]
🧪 Notes:
- The callback must usually return an array (or something traversable like a collection).
- You can use this on multi-dimensional arrays, Eloquent collections, etc.
✅ Summary
Method Returns arrays per item? Flattened output? map()❌ Yes ❌ No flatMap()✅ Yes (merged results) ✅ Yes
Let me know if you'd like an example using Eloquent models or more complex transformations!
- If your callback returns an array,
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.