看了https://learnku.com/articles/6035/laravel55-developing-api-combat
大神文章后 自己项目中一直在用。所以在此感激作者。
但是有一个问题 就是分页返回格式 不统一。 没有status 和code信息。
解决方案:当然是在resource里 添加分页信息
public function list(RecruitGroup $recruitGroup){
$res = $recruitGroup->getListCollection(Auth::user()->user_id,2);
return $this->success(new ListPageCollection($res));
}
public function getListCollection($creatorId,$pageNum)
{
return $this->select(
'id','pro_name','position_name','number','salary','salary_unit','islong',
'job_begdate','job_enddate','work_time','outwork_time')
->where('creator_id',$creatorId)->orderBy('created_at','desc')
->simplePaginate($pageNum);
}
/**
* Transform the resource collection into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'data' => $this->collection->map(function($recuiteGroup){
return [
'salary_unit' => $this->salaryUnit($recuiteGroup->salary_unit),
];
}),
'next_page_url' => $this->nextPageUrl(),//注意这里不是$this->new_page_url
];
}
下面来看下结果
{
"status": "success",
"code": 200,
"data": {
"data": [
{
"salary_unit": "小时"
},
{
"salary_unit": "月"
}
],
"next_page_url": "http://127.0.0.1:8089/api/v1/recruit/group/list?page=4"
}
}