我正在 Laravel 4 中开发 API,现在当我以 JSON 格式返回分页信息时,它会以这种特定格式返回:
{
"Photos":{
"total":1,
"per_page":15,
"current_page":1,
"last_page":1,
"from":1,
"to":1,
"data":[
{
"id":3,
"moreInfo":"..."
}
]
}
}
但我希望我的 API 以这种格式返回信息:
{
"total":1,
"per_page":15,
"current_page":1,
"last_page":1,
"from":1,
"to":1,
"Photos":[
{
"id":3,
"moreInfo":"..."
}
]
}
相关代码如下:
if (Input::has('page')) {
$limit = (Input::get('limit')) ? Input::get('limit') : 15;
return Response::json([
'Photos' => $photos->paginate($limit)->toArray()
]);
}
起初我没有意识到这实际上有多简单,我尝试通过
Pagination->getItems()
和 Pagination->getCollection()
获取数据。
我意识到我所要做的就是从分页中获取 ['data'] 部分。我的代码现在看起来像:
if (Input::has('page')) {
$limit = (Input::get('limit')) ? Input::get('limit') : 15;
$pagedPhotos = $photos->paginate($limit);
return Response::json([
'total' => $pagedPhotos->getTotal(),
'per_page' => $pagedPhotos->getPerPage(),
'current_page' => $pagedPhotos->getCurrentPage(),
'last_page' => $pagedPhotos->getLastPage(),
'from' => $pagedPhotos->getFrom(),
'to' => $pagedPhotos->getTo(),
'Photos' => $photos->paginate($limit)->toArray()['data']
]);
}
所以去掉
photos
组件:
return Response::json($photos->paginate($limit)->toArray())
在 Laravel 9 中,这工作方式有所不同,要自定义 Paginator 的响应,代码应如下所示:
$myCommunityActivities = CommunityActivity::where('member_id', Auth::user()->id)->paginate(10);
$results = [
'total' => $myCommunityActivities->total(),
'per_page' => $myCommunityActivities->perPage(),
'current_page' => $myCommunityActivities->currentPage(),
'last_page' => $myCommunityActivities->lastPage(),
'activities' => $myCommunityActivities->items()
];
return response()->json($results, 200);
对于最新的 Laravel 10,以下解决方案是最合适的:
app/Pagination/CustomPaginator.php
<?php
namespace App\Pagination;
use Illuminate\Pagination\LengthAwarePaginator;
class MyPaginator extends LengthAwarePaginator
{
/**
* Get the instance as an array.
*
* @return array
*/
public function toArray()
{
return [
'data' => $this->items->toArray(),
'current_page' => $this->currentPage(),
'from' => $this->firstItem(),
'last_page' => $this->lastPage(),
'per_page' => $this->perPage(),
'to' => $this->lastItem(),
'total' => $this->total(),
];
}
}
然后在
App\Providers\AppServiceProvider
:
use App\Pagination\MyPaginator;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Contracts\Pagination\LengthAwarePaginator as LengthAwarePaginatorContract;
public function register()
{
$this->app->alias(MyPaginator::class, LengthAwarePaginator::class);
$this->app->alias(MyPaginator::class, LengthAwarePaginatorContract::class);
}