phplaravellaravel-7laravel-eloquent-resource

Laravel Eloquent API Resources: remove "data" key from response (collection)


I've Eloquent API Resource UserResource. When I try run something like this code:

$users = User::paginate(10);
return UserResource::collection($users);

Response will be like this:

{
    "data": [
        {
            "name": "Fatima Conroy",
            "email": "ocie.stark@example.org"
        },
        {
            "name": "John Doe",
            "email": "john.doe@example.org"
        }
    ]
}

How I can remove data key or rename it the get something like this response?

[
    {
        "name": "Fatima Conroy",
        "email": "ocie.stark@example.org"
    },
    {
        "name": "John Doe",
        "email": "john.doe@example.org"
    }
]

Solution

  • To get all the data just use ->all()

    UserResource::collection($users)->all()
    

    You can see more in the official doc about collections where it's explained that using all() gets you the the underlying array represented by the collection.