Home > Enterprise >  How to groupBy the collection of Laravel with the nested field of type array?
How to groupBy the collection of Laravel with the nested field of type array?

Time:03-27

I have this collection, and I want to change this data in order that the key will be the branches id and the value will be the items:

{
    "data": [
        {
            "id": 5020,
            "category_id": 577,
            "branches": [
             {
               "id": 7,
               "title": "water",
             },
             {
               "id": 6,
               "title": "vegetable",
             }, 
        },
        {
            "id": 5025,
            "category_id": 577,
            "branches": [
             {
               "id": 7,
               "title": "water",
             },
        }
     ]
}

I want to group by this data by branches -> id , something like this:

{
    "data": [
        "7" : [
               {
                 "id": 5020,
                 "category_id": 577,
                 "branches": [
                    {
                       "id": 7,
                       "title": "water",
                    },
                    {
                       "id": 6,
                       "title": "vegetable",
                    }, 
               },
              {
                "id": 5025,
                "category_id": 577,
                "branches": [
                  {
                    "id": 7,
                    "title": "water",
                  },
                ] 
             }
           ],
        "6" : [
               {
                 "id": 5020,
                 "category_id": 577,
                 "branches": [
                    {
                       "id": 7,
                       "title": "water",
                    },
                    {
                       "id": 6,
                       "title": "vegetable",
                    }, 
               },

           ],
}

How can I use the group By method of collection in Laravel? I want to have data like this and my data is the type of collection

CodePudding user response:

You can use a callback in groupBy method to provide custom logic.

Example:

collect($data)->groupBy(fn($item, $key) => $item['branches'][0]['id']);

But in this example I want to suggest you to use loop:

$myGroups = [];
foreach($data as $item) {
  foreach($item['branches'] as $branch) {
    $myGroups[$branch['id']][] = $item;
  }
}
  • Related