【问题标题】:Laravel Resource API customize outer data wrapper $wrapLaravel 资源 API 自定义外部数据包装器 $wrap
【发布时间】:2020-09-30 15:44:19
【问题描述】:

我正在尝试为使用 Laravel 资源获取的资源重命名数据包装器。我在文档here 中阅读了您应该如何做,所以我做了:

ScanResource.php

class ScanResource extends JsonResource
{
public static $wrap = 'scan';
/**
 * Transform the resource into an array.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
public function toArray($request)
{
    //return parent::toArray($request);
    return ['id' => $this->id,
                    'rftag' => $this->rftag,
                    'jc_number' => $this->jc_number,
                    'station' => $this->station,
                    'agent' => $this->agent,
                    'created_at' => $this->created_at->format('d/m/Y H:i:s'),
                    'updated_at' => $this->updated_at->format('d/m/Y'),];
}
}

AppServiceProvider.php

class AppServiceProvider extends ServiceProvider
{
public function boot()
{
    //Paginator::useBootstrapThree();
    Schema::defaultStringLength(191);
    //JsonResource::withoutWrapping();
    //Resource::withoutWrapping();
    ScanResource::withoutWrapping();
}

public function register()
{
    //
}
}

这就是我试图在我的控制器中获取资源的方式:

public function show($id)
{
    $product = ScanDetail::find($id);

    if (is_null($product)) {
        return $this->sendError('Scan details not found.');
    }

    return $this->sendResponse(new ScanResource($product), 'Scan info retrieved successfully.');
}

目前我正在使用 Postman 获取以下 JSON:

{
"success": true,
"data": {
    "id": 1,
    "rftag": "E200203204205212165166",
    "jc_number": "15",
    "station": "Repairing",
    "agent": "kbailey",
    "created_at": "11/06/2020 01:29:53",
    "updated_at": "11/06/2020"
},
"message": "Scan info retrieved successfully."
}

但我想要:

{
    "success": true,
    "scan": {
        "id": 1,
        "rftag": "E200203204205212165166",
        "jc_number": "15",
        "station": "Repairing",
        "agent": "kbailey",
        "created_at": "11/06/2020 01:29:53",
        "updated_at": "11/06/2020"
    },
    "message": "Scan info retrieved successfully."
}

我试过thisthisthisthisthisThis 不是我使用的,所以我认为它不会起作用。我还尝试将我的 toArray 修改为:

return [
        'scan'=>['id' => $this->id,
                    'rftag' => $this->rftag,
                    'jc_number' => $this->jc_number,
                    'station' => $this->station,
                    'agent' => $this->agent,
                    'created_at' => $this->created_at->format('d/m/Y H:i:s'),
                    'updated_at' => $this->updated_at->format('d/m/Y'),]
        ];

但它提供以下 JSON:

{
"success": true,
"data": {
    "scan": {
        "id": 1,
        "rftag": "E200203204205212165166",
        "jc_number": "15",
        "station": "Repairing",
        "agent": "kbailey",
        "created_at": "11/06/2020 01:29:53",
        "updated_at": "11/06/2020"
    }
},
"message": "Scan info retrieved successfully."
}

同样,这不是我想要的,因为我将使用 api 调用从数据库中获取不同的资源。所以我想定制外包装。任何帮助是/将不胜感激。提前致谢。

【问题讨论】:

    标签: php json laravel laravel-7


    【解决方案1】:

    在你的控制器里改成这个

    return ['scan' => YourResource::collection(YourModel::get())];
    

    并在您的 AppServiceProvider.php 文件中添加此

    <?php
    
    namespace App\Providers;
    
    use Illuminate\Support\ServiceProvider;
    use Illuminate\Http\Resources\Json\JsonResource; // this
    
    class AppServiceProvider extends ServiceProvider
    {
        public function register()
        {
            JsonResource::withoutWrapping(); // and this
        }
    }
    
    

    希望它对你有用:)

    【讨论】:

      【解决方案2】:

      您无需在 AppServiceProvider.php

      中执行任何操作

      您只需要创建 ScanResource.php 如下:

      <?php
      
      namespace App\Http\Resources;
      
      use Illuminate\Http\Resources\Json\JsonResource;
      
      class ScanResource extends JsonResource
      {
          /**
           * The "data" wrapper that should be applied.
           *
           * @var string
           */
      
          public static $wrap = 'scan';
          /**
           * Transform the resource into an array.
           *
           * @param  \Illuminate\Http\Request  $request
           * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
           */
          public function toArray($request)
          {        
              return [
                  'id' => $this->id,
                  'rftag' => $this->rftag,
                  'jc_number' => $this->jc_number,
                  'station' => $this->station,
                  'agent' => $this->agent,
                  'created_at' => $this->created_at->format('d/m/Y H:i:s'),
                  'updated_at' => $this->updated_at->format('d/m/Y')
              ];
          }
          public function with($request)
          {
              return [
                  "success" => true,
                  "message": "Scan info retrieved successfully."   
              ];
          }
      }
      

      您需要在 ScanController.php 中使用该 ScanResource.php,如下所示

      // use the namespace at the top
      use App\Http\Resources\UserResource;
      
      // add the below action in the controller.
      public function show($id)
      {
           $scan= Scan::find($id);
           return new ScanResource($scan);
      }
      

      我已经在我的邮递员中测试了代码,我得到了以下输出

      {
          "scan": {
              "id" : 7,
              "rftag" : "abcde",
              "jc_number" :"AB123FG" ,
              "station" : "abc",
              "agent" : "Stanton Satterfield",
              "created_at": "29/10/2021 05:18:42",
              "updated_at": "29/10/2021 05:18:42"
          },
          "success" : true,
          "message": "Scan info retrieved successfully."   
      }
      

      【讨论】:

        猜你喜欢
        • 2017-01-29
        • 2021-10-15
        • 2021-11-09
        • 2018-07-07
        • 2020-11-14
        • 2018-06-14
        • 2020-12-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多