Laravel5.5 API 资源 怎么获取分页信息?
https://learnku.com/docs/laravel/5.5/eloquent-resources#分页
在文档所说的通过分页信息在UserCollection 中需要怎么获取啊?哪位大神给指点一下。谢谢
Route::get('/users', function () {
return new UserCollection(User::paginate(2));
});
namespace App\Http\Resources\User;
use Illuminate\Http\Resources\Json\ResourceCollection;
class UserCollection extends ResourceCollection
{
/**
*
*/
public function toArray($request)
{
return [
'data'=>UserResource::collection($this->collection),
"links"=>[ //这里的分页信息需要怎么获取啊?
"first"=> '',
"last"=> "http://example.com/pagination?page=1",
"prev"=> null,
"next"=> null
],
"meta"=>[ //这里的分页信息需要怎么获取啊?
"current_page"=> 1, //怎么获取当前是第几页?
"from"=> 1,
"last_page"=> 1,
"path"=> "http://example.com/pagination",
"per_page"=> 15,
"to"=> 10,
"total"=> 10
]
];
}
}
高认可度评论:
不管是使用
Resource::collection()
还是new ResourceCollection()
,只要你传入继承了\Illuminate\Contracts\Pagination\Paginator
的分页数据 ,Resource 就会自动把分页数据的 links 和 meta 处理好。如果你要手动处理,也可以直接使用
等直接调用 Paginator 的方法。
已解决 原因在
controller
层返回的时候不能用return reaponse()->json(['status'=>'xxx','result'=>new UserCollection(User::paginate(2))])
,我也不知道为什么只是把它去掉就显示了 例如:return new UserCollection(User::paginate(2))
@無限之秋 好的,谢谢,我看一下
为什么不通过路由->闭包的形式就拿不到分页数据呢,我是路由到对应控制器中的方法,不知道想要拿到分页数据有没有什么解决方法呢? @無限之秋
@無 你有解决这个问题吗
@meitesi 分页信息在某些情况丢失的情况
刚碰到,加上业务状态码,就会没有分页。
@manen 有解决方法吗?
@meitesi 这个问题有解决吗