管腔6:如何重构管腔上响应分页的数据



我花了很多时间来解决这个问题,我如何用流明重新构建响应json分页的数据?我应该在API资源和转换器之间使用哪一个?照明分页?

我的PersonController,我尝试使用LengthAwarePaging

use AppModelPerson;
use IlluminatePaginationLengthAwarePaginator;
use IlluminateHttpRequest;
use IlluminateSupportCollection;
public function index(Request $request)
{
$results = Person::all();
$data = array();
$currentPage = LengthAwarePaginator::resolveCurrentPage();
$collection = new Collection($results);
$per_page = 1;
$currentPageResults = $collection->slice(($currentPage-1) * $per_page, $per_page)->all();
$data = new LengthAwarePaginator($currentPageResults, count($collection), $per_page);
$data->setPath($request->url());
return $data;
}

实际响应

{
"current_page": 1,
"data": [
{
"id": 1,
"type": "persons",
"attributes": {
"name": "andrew",
"country": "new zealand",
"gender": "male"
},
}
],
"first_page_url": "http://localhost:8000/person?page=1",
"from": 1,
"last_page": 50,
"last_page_url": "http://localhost:8000/person?page=50",
"next_page_url": "http://localhost:8000/person?page=2",
"path": "http://localhost:8000/person",
"per_page": 1,
"prev_page_url": null,
"to": 1,
"total": 50
}

但我所期望的的反应

{
"meta": {
"count": 5,
"total": 20
},
"links": {
"first": "http:localhost:8000/api/v1/persons?page[limit]=10&page[offset]=0",
"last": "http:localhost:8000/api/v1/persons?page[limit]=10&page[offset]=10",
"next": "http:localhost:8000/api/v1/persons?page[limit]=10&page[offset]=10",
"prev": "null"
},
"data": [
{
"type": "persons",
"id": "1",
"attributes": {
"name": "andrew",
"country": "new zealand",
"gender": "male"
},
"links": {
"self": "http:localhost:8000/api/v1/persons/1/"
}
}
]
}

我该怎么办?

其实很简单

您可以返回以下内容,而不是返回$data

return response()->json([
'meta' => [
"count" => count($collection),
"total" => $data->total
],
'links' => [
"first" => $data->first_page_url,
"last" => $data->last_page_url,
"next" => $data->next_page_url,
"prev" => $data->prev_page_url
],
'data' => $data->data
]);

最新更新