如果您想使用自定义键而不是数据,您可以在资源类上定义 $wrap 属性:
<?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';
}
如果您想禁用“数据”键而不是数据,您可以在资源类上定义 $wrap = null属性:
<?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;
}
如果您想禁用最外层资源的包装,您可以在基础资源类上使用 withoutWrapping 方法。通常,您应该从 AppServiceProvider 或其他服务提供者调用此方法,该服务提供者会在对应用程序的每个请求中加载:
<?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"
}
}
您也可以参考以下官方链接了解更多信息:
https ://laravel.com/docs/8.x/eloquent-resources#data-wrapping