Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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": "[email protected]"
        },
        {
            "name": "John Doe",
            "email": "[email protected]"
        }
    ]
}

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

[
    {
        "name": "Fatima Conroy",
        "email": "[email protected]"
    },
    {
        "name": "John Doe",
        "email": "[email protected]"
    }
]
like image 945
Andreas Hunter Avatar asked Mar 03 '23 17:03

Andreas Hunter


1 Answers

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.

like image 140
Alexandre Elshobokshy Avatar answered Mar 05 '23 15:03

Alexandre Elshobokshy