如何将自定义属性添加到 Laravel 分页 json 响应

How to add custom properties to Laravel paginate json response

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

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对象中提取一些数据,这是[=18的输出=] 来自 this resource,但我无法理解它如何能够从 LengthAwarePaginator 获取一个数组,该数组包含 json 对象中的结果键?!

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

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

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"
}
}

如果您直接使用分页数据进行响应,更好的选择是将其包装在 Resource Collection and adding 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,您的响应在从控制器返回时会自动转换为 JSON。