Reputation: 5024
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]"
}
]
Upvotes: 8
Views: 5685
Reputation: 444
If you would like to use a custom key instead of data, you may define a $wrap attribute on the resource class:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class User extends JsonResource
{
/**
* The "data" wrapper that should be applied.
*
* @var string
*/
public static $wrap = 'user';
}
If you would like to disable "data" key instead of data, you may define a $wrap = null attribute on the resource class:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class User extends JsonResource
{
/**
* The "data" wrapper that should be applied.
*
* @var string
*/
public static $wrap = null;
}
If you would like to disable the wrapping of the outermost resource, you may use the withoutWrapping method on the base resource class. Typically, you should call this method from your AppServiceProvider or another service provider that is loaded on every request to your application:
<?php
namespace App\Providers;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
JsonResource::withoutWrapping(); // This command removes "data" key from all classes extended from "JsonResource"
user::withoutWrapping(); // This command removes "data" key from only "user"
}
}
You can also refer to the official link below for more information: https://laravel.com/docs/8.x/eloquent-resources#data-wrapping
Upvotes: 8
Reputation: 10922
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.
Upvotes: 9