我有以下简单的索引方法:
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
对象中提取一些数据它是 this resource 的 Poll::paginate(2)
的输出,但我无法理解它如何从 LengthAwarePaginator
获取一个数组,该数组保存 json 对象中的结果键?!
最佳答案
来自被关注的resource above ,json()
方法接受一个数组,我猜,如果参数不是数组,它会尝试将其转换为数组,特别是如果它是像 LengthAwarePaginator
这样的对象,所以它可能会使用toArray()
方法。
我尝试替换 return response()->json(Poll::paginate(2),200)
与 return response()->json(Poll::paginate(2)->toArray,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": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dbb7b2b4b59bbea3bab6abb7bef5b8b4b6" rel="noreferrer noopener nofollow">[email protected]</a>"
}
}
关于json - 如何向 Laravel 分页 json 响应添加自定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52559732/