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

Viewed 13072

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"
}
6 Answers

Add this to your resource

public static $wrap = null;

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.

Answering as I keep stumbling on the same problem myself.

The easiest way to return a Laravel resource without the data wrap is to simply return it in a JSON response. So instead of doing:

return new UserResource($user);

You would do:

return response()->json(new UserResource($user));

This way you also don't have to worry about stuffing your AppServiceProvider with a lot of calls to the withoutWrapping method.

To remove the data wrapper for all resources inside your project just add:

use Illuminate\Http\Resources\Json\JsonResource    

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

Inside the boot method of your AppServiceProvider.php.

this worked for me

return UserResource::make($user)->toArray($request);

and for collection

return UserResource::collection($users)->collection;

For some reason this works:

$user = User::find(1);

return UserResource::make($user)->resolve();

Without ->resolve() it's not working.

Related