Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

sharadrsoni's avatar

Question regarding Eloquent: API Resources

Hi All, I am newbie in Laravel. I am using laravel as a REST End Point, I use Eloquent: API Resources for transforming my data to json.

I am using Collection and Resource to parse my data came from my query. So below is the structure of my response:

data:
    0
        id
        name
    1
        id
        name

Now I need to have some categorization in the data, hence I require the data structure to be in below format

data:
    24H
        0
            id
            name
        1
            id
            name
    7D
        0
            id
            name
        1
            id
            name

I tried couple of ways to accomplish this, the static way I tried for testing was to change the ResourceCollection's toArray method and append the key 24H for the data we get.

But I know that is not correct and generic way.

I would like to know how I can achieve the above response format in generic and extensible manner.

Your help is much appreciated.

Thanks.

0 likes
1 reply
bugsysha's avatar

@sharadrsoni you can use the data returned by Resource::collection and then group it before returning it as response. Something like following should work

return UserResource::collection($users)->groupBy(fn () => ...);
1 like

Please or to participate in this conversation.