1

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.

3 Answers 3

3

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;
    });
}
Sign up to request clarification or add additional context in comments.

Comments

3

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'])
        ]);
    });
}

2 Comments

it return error Trying to get property 'children' of non-object on line 'children' => collect($voucher->children)
Oh, sorry, fixed it.
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"
      }
    }
  ]
}

6 Comments

That's exactly what the thread owner did.
but he wants children to be object. Isnt it happen from my code @shaedrich ?
he says it can't convert children => [...] to collection. . So my answer works as he wanted.
No, they want path, active, name and icon to be object as far as I can see. And even if you were right, it wouldn't require an answer but a comment that the thread owner does everything right.
his code base dosent make children as a object
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.