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 :

JavaScript
JavaScript

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:

JavaScript

map

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

JavaScript

flatten

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

JavaScript

sortKeys

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

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement