ItSolutionStuff.com

Laravel Collection Flatten Method Example

By Hardik Savani • April 16, 2024
Laravel

In this article we will cover on how to implement laravel collection flatten example. if you want to see example of laravel collection flatten one level then you are a right place. i would like to share with you laravel collection flatten array. you can see laravel eloquent flatten.

The flatten method will help to convert a multi-dimensional collection into a single dimension.

I will give you simple examples of flatten colletion in laravel. so you can easily use it with your laravel 5, laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 application. so let's see bellow example that will helps you lot.

Syntax:

$collecton->flatten(

$depth INT

);

Laravel Collection flatten() Example

public function index()

{

$collection = collect([

'name' => 'Hardik',

'role' => ['admin', 'manager', 'superadmin'],

'multi' =>

[

'one',

'two' => ['two1', 'two3'],

'three'

],

]);

$flattened = $collection->flatten();

dd($flattened);

}

Output:

Illuminate\Support\Collection Object

(

[items:protected] => Array

(

[0] => Hardik

[1] => admin

[2] => manager

[3] => superadmin

[4] => one

[5] => two1

[6] => two3

[7] => three

)

)

Laravel Collection flatten() with depth Example

public function index()

{

$collection = collect([

'Apple' => [

['name' => 'iPhone 7S', 'brand' => 'Apple'],

],

'Vivo' => [

['name' => 'V-85', 'brand' => 'Vivo']

],

]);

$flattened = $collection->flatten(1);

dd($flattened);

}

Output:

Illuminate\Support\Collection Object

(

[items:protected] => Array

(

[0] => Array

(

[name] => iPhone 7S

[brand] => Apple

)

[1] => Array

(

[name] => V-85

[brand] => Vivo

)

)

)

I hope it can help you...

Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

Laravel Collection Except() Method Example

Read Now →

Laravel Collection Duplicates Method Example

Read Now →

Laravel Collection diff(), diffAssoc() and diffKeys() Example

Read Now →

Laravel Collection Concat Method Example

Read Now →

Laravel Collection Count and CountBy Method Example

Read Now →

Laravel Collection GroupBy with Examples

Read Now →

Laravel Collection first() and firstWhere() Methods Example

Read Now →

Laravel Collection contains() and containsStrict() Methods Example

Read Now →

Laravel Collection Forget | Remove Item from Collection Laravel

Read Now →

Laravel Collection Push() and Put() Example

Read Now →