laraveleloquentlaravel-7

Laravel eloquent api resource remove `data` key (no collection)


I have custom eloquent api resource for user. For example when I use this resource

Code

$user = $request->user();
return new UserResource($user);

Then on response I get:

{
    "data": {
        "name": "Margarete Daniel",
        "email": "goldner.berniece@example.net",
        "verified": "2020-03-20T07:15:56.000000Z"
    }
}

How I can change api resource and get example response:

{
    "name": "Margarete Daniel",
    "email": "goldner.berniece@example.net",
    "verified": "2020-03-20T07:15:56.000000Z"
}

Solution

  • You can disable data wrapping by calling the withoutWrapping static method of your resource in the AppServiceProvider. In your case it will be:

    public function boot()
    {
        UserResource::withoutWrapping();
    }
    

    You can refer to Laravel documentation about data wrapping for more explanation.