Skip to content
Advertisement

How to build this Laravel Eloquent Query

I want to build a nested array from a simple table with Laravel Eloquent, but i couldn’t.

So basically below is a snap shot of my table

enter image description here

and this is the array I want to build

enter image description here

Advertisement

Answer

You can use some methods from collection :

$result = $data->groupBy(['market_id', 'base_currency', 'currency_id'])
    ->map(function ($item) {
        return $item->map(function ($item) {
            return $item->map(function ($item) {
                return $item->map(function ($item) {
                    return $item['currency_id'];
                });
            })->flatten();
        })->sortKeys();
    });

dd($result->toArray());
array:1 [
  1 => array:2 [
    1 => array:2 [
      0 => 2
      1 => 3
    ]
    2 => array:2 [
      0 => 1
      1 => 2
    ]
  ]
]

Explanation

groupBy

The groupBy method groups the collection’s items by a given key. Multiple grouping criteria may be passed as an array. Each array element will be applied to the corresponding level within a multi-dimensional array:

$data->groupBy(['market_id', 'base_currency', 'currency_id']);

map

The map method iterates through the collection and passes each value to the given callback.

->map(function ($item) {
    return $item;
});

flatten

The flatten method flattens a multi-dimensional collection into a single dimension:

->flatten()

sortKeys

The sortKeys method sorts the collection by the keys of the underlying associative array:

->sortKeys()
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement