Collection::collapse

Merges a collection of arrays or collections into one flat collection, one level deep.

Signature
collapse(): Collection
  • Added in Laravel 5.0

Return value

Collection<int, mixed>A new collection containing the items of every nested array or collection, merged one level deep.

Changelog

  • PHP 11.xcollapseWithKeys() was added for the case where the outer keys must be kept rather than discarded.

collapse() takes a collection whose items are themselves arrays or collections and merges them into a single flat collection. It is the natural inverse of chunk() and the usual follow-up to groupBy() or a batched fetch.

One level, always

It descends exactly one level. Collapsing [[[1,2]], [[3,4]]] gives [[1,2],[3,4]], not [1,2,3,4]. When you need to go all the way down, or an unknown number of levels, use flatten() — it takes an optional depth and recurses. Reach for collapse() precisely when one level is what you mean.

Key behaviour

Internally it is array_merge() over the nested items, which gives it that function's key semantics. Integer keys are discarded and renumbered from zero, so no data is lost when the inner arrays are lists. String keys collide: if two inner arrays both hold a 'php' key, the later one silently wins and the earlier value disappears. Use collapseWithKeys() (Laravel 11+) when the outer keys matter, or flatten() when you want every value regardless of key.

Non-iterable items

Scalars in the outer collection are skipped rather than raising an error, so a stray string quietly vanishes from the result.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Merge several pages of API results back into one flat list.
  • Undo a groupBy() once each group has been processed.
  • Flatten a collection of per-model tag arrays into a single tag list.

Frequently asked questions

What is the difference between collapse() and flatten() in Laravel?

collapse() merges exactly one level and keeps string keys, while flatten() recurses to any depth (or the depth you pass) and discards keys entirely. Use collapse() for a collection of arrays and flatten() for arbitrarily deep nesting.

Why did collapse() lose some of my values?

Because it merges with array_merge semantics, so two inner arrays sharing a string key leave only the later value. Use collapseWithKeys() to keep the outer keys, or flatten() to keep every value.

Does collapse() work on a collection of collections?

Yes — nested Collection instances are unwrapped the same way as plain arrays, so a collection of collections flattens one level just as a collection of arrays does.

More examples

collapse() versus flatten()

collapse() merged the two outer arrays and kept the distinct string keys a and b, leaving the numeric arrays intact. flatten() with no depth recursed to the scalars. flatten(1) went one level but threw the keys away, which is the difference from collapse().

Example · php
<?php

$data = collect([
    ['a' => [1, 2]],
    ['b' => [3, 4]],
]);

// One level: the inner numeric arrays are still arrays.
print_r($data->collapse()->all());
// Array ( [a] => Array ( [0] => 1 [1] => 2 )
//         [b] => Array ( [0] => 3 [1] => 4 ) )

// All the way down.
print_r($data->flatten()->all());
// Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )

// Exactly one level down, keys discarded.
print_r($data->flatten(1)->all());
// Array ( [0] => Array ( [0] => 1 [1] => 2 )
//         [1] => Array ( [0] => 3 [1] => 4 ) )

Rejoining grouped Eloquent results

groupBy() produced a collection of collections keyed by author id. After trimming each group, collapse() merges them back into one flat collection; because the models are stored under integer keys they are renumbered rather than overwritten. Needs a booted application with a database.

Example · php
<?php

$byAuthor = Post::published()->get()->groupBy('author_id');

// Keep the three newest posts from each author, then flatten back.
$featured = $byAuthor
    ->map(fn (Collection $posts) => $posts->sortByDesc('published_at')->take(3))
    ->collapse()
    ->sortByDesc('published_at')
    ->values();

echo $featured->count(), PHP_EOL;
// 12

echo $featured->first()->title, PHP_EOL;
// "Release notes for 12.4"

Discussion

  • Be the first to comment on this lesson.