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

knubbe's avatar
Level 36

Modify api resource response with new key above data collection

Is there any way to return api resouce like this:

"items": {
    "sum_of_products": 10000,
        "data": [
            {
                "product_id": 1,
                "price": 50.000
            },
            {
                "product_id": 1,
                "price": 50.000
             },
         ]
     },
0 likes
6 replies
bugsysha's avatar
bugsysha
Best Answer
Level 61

You can see it here in the docs.

public function toArray($request)
{
    return [
        'data' => $this->collection,
        'sum_of_products' => $codeToReturnTheSum,
    ];
}
1 like
knubbe's avatar
Level 36

Ok but what $this->collection returns? In resource class I have some key modifications, I also have some relation data collection

bugsysha's avatar

It returns the collection of resources. If it was UserResource, then it would return collection of Users.

knubbe's avatar
Level 36

Yes but I am for example in UserResource and my toArray method has different structure and you tell me to set differently

knubbe's avatar
Level 36

Ok, now I understand ;) Thanks

Please or to participate in this conversation.