Laravel Collection Flatten Method Example
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
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel Collection Except() Method Example
- Laravel Collection Duplicates Method Example
- Laravel Collection diff(), diffAssoc() and diffKeys() Example
- Laravel Collection Concat Method Example
- Laravel Collection Count and CountBy Method Example
- Laravel Collection GroupBy with Examples
- Laravel Collection first() and firstWhere() Methods Example
- Laravel Collection contains() and containsStrict() Methods Example
- Laravel Collection Forget | Remove Item from Collection Laravel
- Laravel Collection Push() and Put() Example