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

peterdickins's avatar

How to return resource without wrapping each row in curly braces

Hi,

I have a table called user_metadata which may contain many rows for a user. I have created an end point that returns all data for a user in the controller:

/**
 * @return JsonResponse
 */
public function index(): JsonResponse
{
    return $this->generateResponse(UserMetadataResource::collection(UserMetadata::where('user_id', request()->input('user_id'))->get()), 200);
}

Here is my UserMetadataResource:

class UserMetadata extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param Request $request
     * @return array
     */
    public function toArray($request): array
    {
        return [
            $this->name => $this->value
        ];
    }
}

And this is the response:

{
    "status": 200,
    "data": [
        {
            "data_item_1": "Value 1"
        },
        {
            "data_item_2": "Value 2"
        },
    ],
    "message": "success"
}

How can I update the response so that it is returning all rows as one object rather than an array of objects?

0 likes
1 reply
tuneless's avatar
tuneless
Best Answer
Level 2

https://laravel.com/docs/9.x/eloquent-resources#resource-collections

Note that this does not allow any addition of custom meta data that may need to be returned with your collection. If you would like to customize the resource collection response, you may create a dedicated resource to represent the collection:

I think you need a dedicated resource collection here and in there you have like in the doc:

return [
            'data' => $this->collection,
             ...
];
1 like

Please or to participate in this conversation.