Vivek Mistry šŸ‘‹

I’m a Certified Senior Laravel Developer with 6+ years of experience , specializing in building robust APIs and admin panels, frontend templates converting them into fully functional web applications.

Book A Call
  • 15 Nov, 2025
  • 197 Views
  • The quickest explanation of when and why you should prefer flatMap() over array_column().

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

Share: