How to flatten a collection in Laravel

Categorized as Laravel Tagged

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']

Leave a reply

Your email address will not be published. Required fields are marked *