Laravel 5 Collections: Reducing a Multi-Dimensional Collection to a Single Dimension Losing Keys With flatten

1 min read

The flatten method will return a new Collection instance representing a flattened version of the original collection's items. The flatten method internally makes use of the "Illuminate\Support\Arr::flatten($array)" helper method. The flatten method will not preserve any keys from the original collection.


1public function flatten(
2 $depth = INF

Example Use

The following example demonstrates the usage of the flatten method:

1use Illuminate\Support\Collection;
3// Create a new collection instance.
4$collection = new Collection([
5 'first',
6 'second' => [
7 'nested',
8 'array',
9 [
10 'deeply',
11 'nested'
12 ]
13 ],
14 'third' => 'some-value'
17// Flatten the original collection.
18$flattenedCollection = $collection->flatten();

The $flattenedCollection variable will hold an instance of the Collection class and will have a value similar to the following output:

2 protected 'items' =>
3 array
4 0 => string 'first'
5 1 => string 'nested'
6 2 => string 'array'
7 3 => string 'deeply'
8 4 => string 'nested'
9 5 => string 'some-value'

It is obvious in the above output that the flatten method does not preserve any of the original keys, and will even flatten deeply nested arrays.

Thanks for taking the time to read this post! If you found this article useful and want to help support more work like this, please consider sponsoring my work on GitHub, or by checking out some merch.

 Sponsor on GitHub  Shop Merch