How to flatten a collection in Laravel
Categorized as Laravel
Here is a cool trick with the flatten
method, which can convert your multi-dimensional Laravel collection into a flattened (single dimension) one. See the code below:
$collection = collect([
'name' => 'programming languages',
'languages' => [
'php', 'javascript', 'python'
]
]);
$flattened = $collection->flatten();
$flattened->all();
// ['programming languages', 'php', 'javascript', 'python']