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
            ]
        ];
    }
}
meitesi
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 11
// 加个->resource可以保留分页信息
return [
    'data' => UserResource::collection(User::paginate(n))->resource,
    'status' => 123,
    'code' => 123,
    'message' => 'Some msg',
];

return [
    'data' => UserResource::collection(User::paginate(n))->toResponse(Request $request)->getData(),
    'status' => 123,
    'code' => 123,
    'message' => 'Some msg',
];
3年前 评论

不管是使用 Resource::collection() 还是 new ResourceCollection() ,只要你传入继承了 \Illuminate\Contracts\Pagination\Paginator 的分页数据 ,Resource 就会自动把分页数据的 links 和 meta 处理好。

如果你要手动处理,也可以直接使用

$this->total()
$this->currentPage()
$this->lastPage()
...

等直接调用 Paginator 的方法。

6年前 评论
meitesi

已解决 原因在controller层返回的时候不能用
return reaponse()->json(['status'=>'xxx','result'=>new UserCollection(User::paginate(2))]),我也不知道为什么只是把它去掉就显示了 例如:return new UserCollection(User::paginate(2))

6年前 评论
meitesi

@無限之秋 好的,谢谢,我看一下

6年前 评论

为什么不通过路由->闭包的形式就拿不到分页数据呢,我是路由到对应控制器中的方法,不知道想要拿到分页数据有没有什么解决方法呢? @無限之秋

5年前 评论

@無 你有解决这个问题吗

4年前 评论

@meitesi 分页信息在某些情况丢失的情况

4年前 评论

刚碰到,加上业务状态码,就会没有分页。

4年前 评论

@manen 有解决方法吗?

3年前 评论
yxuefeng 3年前
// 加个->resource可以保留分页信息
return [
    'data' => UserResource::collection(User::paginate(n))->resource,
    'status' => 123,
    'code' => 123,
    'message' => 'Some msg',
];

return [
    'data' => UserResource::collection(User::paginate(n))->toResponse(Request $request)->getData(),
    'status' => 123,
    'code' => 123,
    'message' => 'Some msg',
];
3年前 评论

@meitesi 这个问题有解决吗

3年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!