Laravel Eloquent API 资源:从响应(集合)中删除“数据”键

And*_*ter 3 php laravel laravel-eloquent-resource laravel-7

我有 Eloquent API Resource UserResource。当我尝试运行这样的代码时:

$users = User::paginate(10);
return UserResource::collection($users);
Run Code Online (Sandbox Code Playgroud)

响应将是这样的:

{
    "data": [
        {
            "name": "Fatima Conroy",
            "email": "ocie.stark@example.org"
        },
        {
            "name": "John Doe",
            "email": "john.doe@example.org"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

如何删除data密钥或重命名它以获得类似此响应的内容?

[
    {
        "name": "Fatima Conroy",
        "email": "ocie.stark@example.org"
    },
    {
        "name": "John Doe",
        "email": "john.doe@example.org"
    }
]
Run Code Online (Sandbox Code Playgroud)

Ale*_*shy 9

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

UserResource::collection($users)->all()
Run Code Online (Sandbox Code Playgroud)

您可以在官方文档中看到有关集合的更多信息,其中解释了使用all()可以获取集合表示的底层数组。


Fer*_*nar 5

如果你想使用自定义键而不是数据,你可以在资源类上定义一个 $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';
    }
Run Code Online (Sandbox Code Playgroud)

如果你想禁用“data”键而不是数据,你可以在资源类上定义一个 $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;
        }
Run Code Online (Sandbox Code Playgroud)

如果您想禁用最外层资源的包装,您可以在基本资源类上使用 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"


    }
}
Run Code Online (Sandbox Code Playgroud)

你也可以参考下面的官方链接了解更多信息:https : //laravel.com/docs/8.x/eloquent-resources#data-wrapping