Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

371
Views
How to convert array and sub array to collection in Laravel?

I want to convert all of my static data to collection in Laravel.

This is my data:

static $menu_list = [
    [
        'path' => 'admin/report/transaction',
        'active' => 'admin/report',
        'name' => 'Report',
        'icon' => 'file-text',
        'children' => [
            'path' => 'admin/report/transaction',
            'active' => 'admin/report/transaction',
            'name' => 'Transaction',
        ],
    ],
];

This function converts my data to array:

public static function menuList()
{
    $menu_list = collect(self::$menu_list)->map(function ($voucher) {
        return (object) $voucher;
    });
}

but function above can only convert main of array, it can't convert children => [...] to collection.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

You need a recursive call.

public static function convertToCollection()
{
    $menu_list = self::menuList(self::$menu_list);
}

public static function menuList($list)
{
    return collect($list)->map(function ($voucher) {
        if(is_array($voucher)) {
          return self::menuList($voucher)
        }
        return $voucher;
    });
}
over 4 years ago · Santiago Trujillo Report

0

You need to use collect() inside map() again:

public static function menuList()
{
    $menu_list = collect(self::$menu_list)->map(function ($voucher) {
        return (object) array_merge($voucher, [
            'children' => collect($voucher['children'])
        ]);
    });
}
over 4 years ago · Santiago Trujillo Report

0

Just add a small code peace to your approach.

  $menu_list = collect(self::$menu_list)->map(function ($voucher) {
             $voucher['children'] = (object) $voucher['children'];
            return (object) $voucher;
        });

Output

   Illuminate\Support\Collection {#574 ▼
  #items: array:1 [▼
    0 => {#573 ▼
      +"path": "admin/report/transaction"
      +"active": "admin/report"
      +"name": "Report"
      +"icon": "file-text"
      +"children": {#567 ▼
        +"path": "admin/report/transaction"
        +"active": "admin/report/transaction"
        +"name": "Transaction"
      }
    }
  ]
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!