The Difference Between collapse() and flatten() in Laravel Collections

The Difference Between collapse() and flatten() in Laravel Collections

Flattening multi dimensional array into an array of items is a common operation in Laravel. If you check the documentation, you'll see there are two methods which look similar.

collapse() and flatten()

As both of these turn an array of arrays into a simple collection, it's easy to think they're the same thing. However, they have very different impacts on the way arrays are structured. Using the wrong one could end up flattening some deeply nested data you didn't want to lose or not being able to access other values correctly.

How collapse() Works

The collapse() method collapses a collection of arrays into a single, flat collection by exactly one level. It can be thought of as combining  multiple arrays.

$matrix = collect([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
]);

$collapsed = $matrix->collapse();

// Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

However, if the nested arrays contain deeper sub-arrays, collapse() leaves those inner sub-arrays unchanged:

$deep = collect([
    [1, [2, 3]],
    [4, [5, 6]],
]);

$collapsed = $deep->collapse();

// Output: [1, [2, 3], 4, [5, 6]]

How flatten() Works

The flatten() method completely flattens the given multi-dimensional collection into a single 1-Dimensional list. By default, the flatten() method is recursive and has an infinite depth, meaning that it pulls out all the scalars from the nested lists or tuples to the top-level list. For example:

$deep = collect([
    'framework' => 'Laravel',
    'details' => [
        'author' => 'Taylor Otwell',
        'releases' => [10, 11, 12],
    ],
]);

$flattened = $deep->flatten();

// Output: ['Laravel', 'Taylor Otwell', 10, 11, 12]

Every internal key and structural array boundary is stripped away, leaving only pure leaf values.

Controlling flatten() Depth

Unlike collapse(), flatten() accepts an optional $depth parameter. You can tell it precisely how many levels of nesting to collapse.

$data = collect([
    'apple',
    ['banana', ['cherry', 'date']],
]);

// Flatten only 1 level
$flatten1 = $data->flatten(1);
// Output: ['apple', 'banana', ['cherry', 'date']]

// Flatten completely (default depth = INF)
$flattenAll = $data->flatten();
// Output: ['apple', 'banana', 'cherry', 'date']

Calling $collection->flatten(1) behaves similarly to collapse() on pure arrays, but there is a major trap when handling associative data.

The Trap: Preserving Associative Structures

The most important difference between these two methods is manifested in case of a list of associative arrays or model attributes.

Let's imagine that you need to merge groups of records, preserving each item's key-value structure:

$departments = collect([
    [
        ['id' => 1, 'name' => 'Kishan'],
        ['id' => 2, 'name' => 'Aman'],
    ],
    [
        ['id' => 3, 'name' => 'Priya'],
    ],
]);

// 1. Using collapse() — Preserves the item objects/arrays
$collapsed = $departments->collapse();
// Result:
// [
//     ['id' => 1, 'name' => 'Kishan'],
//     ['id' => 2, 'name' => 'Aman'],
//     ['id' => 3, 'name' => 'Priya'],
// ]

// 2. Using flatten() without arguments — Destroys the items!
$flattened = $departments->flatten();
// Result:
// [1, 'Kishan', 2, 'Aman', 3, 'Priya']

If you mistakenly run flatten() on a collection of grouped records, it breaks apart each associative entity into raw, disconnected scalar values.

Summary

Feature collapse() flatten()
Flattening Depth Strictly 1 level only Infinite (or custom via $depth)
Accepts Arguments? No Yes (optional integer depth)
Associative Arrays Preserves internal item structure Extracts and flattens all internal values
Best Used For Combining grouped rows or arrays of rows Extracting all scalar leaves into a simple 1D array

Use collapse() when you have an array of arrays (like chunks or grouped DB rows) and want to merge them into one list, retaining the structure of items. Use flatten() when you have deeply nested arrays, and you only want to collect all the innermost leaf values into a 1D list.

Thank you for reading this article 😊

For any query, do not hesitate to comment 💬


Previous Post Next Post

Contact Form