Laravel Collection Flatten Method Example

About Us:

We are from free coder. We are a group of web developers who are passionate about web development. You can learn from us php, laravel, node js, vue js, react js and many other topic on web developement.
we are very happy to help you.
free coder

Today what you are going to learn:

In this article we will cover on how to implement laravel collection flatten lesson. if you want to see lesson 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 lessons of flatten colletion in laravel. so you can easily use it with your laravel 5, laravel 6, laravel 7 and laravel 8 application. so let's see bellow lesson that will helps you lot.

Syntax:

$collecton->flatten(

$depth INT

);

Laravel Collection flatten() Example

public function index()

{

$collection = collect([

'name' => 'Sagor',

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

'multi' =>

[

'one',

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

'three'

],

]);

$flattened = $collection->flatten();

dd($flattened);

}

Result:-

Illuminate\Support\Collection Object

(

[items:protected] => Array

(

[0] => Sagor

[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);

}

Result:-

Illuminate\Support\Collection Object

(

[items:protected] => Array

(

[0] => Array

(

[name] => iPhone 7S

[brand] => Apple

)

[1] => Array

(

[name] => V-85

[brand] => Vivo

)

)

)

thank you very much for following up with me.

Recent Posts

Related Posts