【问题标题】:How to add custom properties to Laravel paginate json response如何将自定义属性添加到 Laravel 分页 json 响应
【发布时间】:2019-03-04 17:04:01
【问题描述】:

我有以下简单的索引方法:

public function index()
    {
       // dd(Poll::paginate(2));
      return response()->json(Poll::paginate(2),200);
    }

该方法的输出类似于以下 json 对象:

{
"current_page": 1,
"data": [
{
"id": 1,
"title": "I suppose?' said Alice. 'Why, you don't know.",
"created_at": "2018-09-14 16:42:11",
"updated_at": "2018-09-14 16:42:11"
},
{
"id": 2,
"title": "Alice; but she knew that it seemed quite.",
"created_at": "2018-09-14 16:42:11",
"updated_at": "2018-09-14 16:42:11"
}
],
"first_page_url": "http://127.0.0.1:8000/polls?page=1",
"from": 1,
"last_page": 6,
"last_page_url": "http://127.0.0.1:8000/polls?page=6",
"next_page_url": "http://127.0.0.1:8000/polls?page=2",
"path": "http://127.0.0.1:8000/polls",
"per_page": 2,
"prev_page_url": null,
"to": 2,
"total": 11
}

我想在"total: 11"属性之后添加另一个数组属性如:

,
"anotherData" : [
   "userId": 1,
   "userName": "john10",
   "message": "This is a message"
]

我已经尝试了解response()->json() 的工作原理,因此它可以从LengthAwarePaginator 对象中提取一些数据,它是Poll::paginate(2)this resource 的输出,但我不能能够理解它如何能够从LengthAwarePaginator 获取一个数组,该数组包含 json 对象中的结果键?!

【问题讨论】:

    标签: json laravel laravel-5 response


    【解决方案1】:

    根据resource abovejson() 方法接受一个数组,我猜如果参数不是数组,它会尝试将其转换为数组,特别是如果它是像LengthAwarePaginator 这样的对象, 所以它可以使用toArray() 方法。

    我尝试用return response()->json(Poll::paginate(2)->toArray,200) 替换return response()->json(Poll::paginate(2),200),然后我得到了相同的输出。因此,我决定将我的 index 方法的代码替换为如下:

    public function index()
        {
            //dd(Poll::paginate(2)->toArray());
            $output = Poll::paginate(2)->toArray();
            $output['userData'] = ['userId' => \Auth::user()->id, 'userEmail' => \Auth::user()->email];
            return response()->json($output,200);
        }
    

    结果输出是:

    ...
    "path": "http://127.0.0.1:8000/polls",
    "per_page": 2,
    "prev_page_url": null,
    "to": 2,
    "total": 11,
    "userData": {
    "userId": 1,
    "userEmail": "lion@example.com"
    }
    }
    

    【讨论】:

      【解决方案2】:

      如果您直接使用分页数据进行响应,更好的选择是将其包装在 Resource Collectionadding meta data 中。

      这就是我实现它的方式。

      CategoryController.php

      public function index()
      {
          return new CategoryCollection(Category::paginate(10));
      }
      

      CategoryCollection.php

      public function toArray($request)
      {
          return [
              'status' => 1,
              'message' => 'Success',
              'data' => $this->collection,
          ];
      }
      

      由于 Collection 扩展了 JsonResource,当从 Controller 返回时,您的响应将自动转换为 JSON。

      【讨论】:

        猜你喜欢
        • 2020-03-22
        • 2014-07-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-18
        • 2012-11-25
        相关资源
        最近更新 更多