Laravel Eloquent API 资源:从响应(集合)中删除 "data" 键

Laravel Eloquent API Resources: remove "data" key from response (collection)

我有 Eloquent API 资源 UserResource。当我尝试 运行 类似这样的代码时:

$users = User::paginate(10);
return UserResource::collection($users);

响应将是这样的:

{
    "data": [
        {
            "name": "Fatima Conroy",
            "email": "ocie.stark@example.org"
        },
        {
            "name": "John Doe",
            "email": "john.doe@example.org"
        }
    ]
}

如何删除 data 键或重命名它以获得类似这样的响应?

[
    {
        "name": "Fatima Conroy",
        "email": "ocie.stark@example.org"
    },
    {
        "name": "John Doe",
        "email": "john.doe@example.org"
    }
]

要获取所有数据,只需使用 ->all()

UserResource::collection($users)->all()

您可以在 official doc about collections 中看到更多信息,其中解释了使用 all() 可以获取集合所代表的基础数组。

如果您想使用自定义键而不是数据,您可以在资源上定义一个 $wrap 属性 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';
    }

如果您想禁用“数据”键而不是数据,您可以在资源 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;
        }

如果您想禁用最外层资源的包装,您可以在基础资源上使用 withoutWrapping 方法 class。通常,您应该从您的 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"


    }
}

也可以参考下方官方link获取更多信息: https://laravel.com/docs/8.x/eloquent-resources#data-wrapping