laravel - ResourceCollection 不包括分页链接

标签 laravel laravel-5.5

评论收藏

class CommentsCollection extends ResourceCollection
{
    public function toArray($request)
    {
        return [
            'data' => $this->collection
        ];
    }
}

CommentsController
public function index()
{
    $post = Post::find(1);
    return ['post'=> $post, 'comments' => new CommentsCollection(Comment::paginate(1))];
}

回复
"comments": {
        "data": [
            {
                "id": 1,
                "content": "First comment",
                "post_id": 6,
                "account_id": 1,
                "created_at": "2018-03-07 02:50:33",
                "updated_at": "2018-03-07 02:50:34"
            }
        ]
    }

当资源使用 ::collection 时会发生这种情况方法甚至 ResourceCollection 作为数组的一部分返回。

如果我们要删除数组并返回纯集合:
return new CommentsCollection(Comment::paginate(1))
一切正常,响应将包括 友情链接 .

为什么 API Resource(使用 collection 方法或 ResourceCollection)在数组中返回时不包含分页信息?

最佳答案

我遇到了这个问题并找到了解决方案检查以下链接以获取解决方案的详细说明

https://laracasts.com/discuss/channels/laravel/paginate-while-returning-array-of-api-resource-objects-to-the-resource-collection?reply=575401

简而言之,请检查以下解决问题的代码片段

$data = SampleModel::paginate(10);
return ['key' => SampleModelResource::collection($data)->response()->getData(true)];

关于laravel - ResourceCollection 不包括分页链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49289379/

相关文章:

php - 从 5.4 升级后,Laravel 5.5 抛出 ReflectionException CustomRequest 类不存在

php - Laravel 5.5 迁移后外键引用关系不显示

php - 分页之前的多维 groupBy 和 orderBy - Laravel 5

创建帐户后无法访问 PHP Laravel 5 用户类属性以发送电子邮件

javascript - 如何获取datatables中数据的 'id'来显示update form中的数据?

php - laravel 5.5 在单列上分组不起作用

php - Laravel 5.5 : PHPUnit (with coverage) doesn't like routes from multiple files and throws "A facade root has not been set". 没有覆盖它是绿色的

php - 找不到 Laravel 测试模拟对象方法

Laravel Dusk 忽略 .env.dusk 和 .env.dusk.local(使用 Valet 和 Laravel 5.5)

php - Laravel 查询生成器获取自定义属性