Laravel Tip: Why flatMap() Is Better Than array_column() for Real Projects
? The Real Problem
In real applications, we often deal with multiple collections of data, each containing sub-arrays.
Example from APIs or DB:
$orders = [
[
'order_id' => 1,
'items' => [
['name' => 'Pen', 'qty' => 2],
['name' => 'Book', 'qty' => 1],
]
],
[
'order_id' => 2,
'items' => [
['name' => 'Pencil', 'qty' => 3],
['name' => 'Marker', 'qty' => 1],
]
],
[
'order_id' => 3,
'items' => [],
],
];
Now you need a single flat list of all items from all orders.
ā Why array_column() Cannot Do This
array_column($orders, 'items');
You get:
[
[ ['Pen'], ['Book'] ],
[ ['Pencil'], ['Marker'] ],
[]
]
$allItems = collect($orders)->flatMap(fn($order) => $order['items']);
$allItems = collect($orders)->flatMap(fn($order) => $order['items']);
Result:
[
['name' => 'Pen', 'qty' => 2],
['name' => 'Book', 'qty' => 1],
['name' => 'Pencil', 'qty' => 3],
['name' => 'Marker', 'qty' => 1],
]
ā All nested arrays merged
ā All items flattened
ā No loops
ā Clean and readable