Laravel Collection Flatten Method Example

Admin   Laravel   136  2020-08-13 04:38:01

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 and laravel 7 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...