我有以下简单的索引方法:
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)
从这一资源,但我无法理解如何做它能够得到一个数组LengthAwarePaginator
保存在JSON生成的密钥目的?!
从上面json()
考虑的资源来看,该方法采用一个数组,我猜想,如果参数不是数组,它会尝试将其转换为数组,特别是如果它是像 一样的对象LengthAwarePaginator
,因此它可能会使用toArray()
方法。
我曾尝试更换return response()->json(Poll::paginate(2),200)
用return response()->json(Poll::paginate(2)->toArray,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": "[email protected]"
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句