Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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": "[email protected]",
        "verified": "2020-03-20T07:15:56.000000Z"
    }
}

How I can change api resource and get example response:

{
    "name": "Margarete Daniel",
    "email": "[email protected]",
    "verified": "2020-03-20T07:15:56.000000Z"
}
like image 662
Andreas Hunter Avatar asked Mar 24 '20 11:03

Andreas Hunter


2 Answers

Add this to your resource

public static $wrap = null;
like image 133
Mustafa Akçakaya Avatar answered Oct 24 '22 15:10

Mustafa Akçakaya


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.

like image 29
Reda Bezzerrouki Avatar answered Oct 24 '22 16:10

Reda Bezzerrouki