mastermindlegion's avatar

Add meta to paginated collection

Hello guys, could you please help me with adding meta to paginated collection?

Here is my provider ExtendCollectionServiceProvider:

    public function boot()
    {
                Collection::macro('paginate', function ($perPage, $total = null, $page = null, $pageName = 'page', $queryParams= []) {
            $page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName);

            return new LengthAwarePaginator($this->forPage($page, $perPage), $total ?: $this->count(), $perPage, $page, [
                'path' => 'articles',
                'pageName' => $pageName,
                'query' => $queryParams
            ]);
        });
    }

Here is controller:

 public function index()
    {
     $collection = new ArticlesCollection(
      ArticleResource::collection(Article::with(['user', 'tags'])->paginate(3)));
     return $collection;
    }

And I got this response, pagination works. I can swap pages, but there is no meta. I dont know, which is the last...

{
"data": [
{
"id": 1,
"user": {
"id": 1,
"full_name": "test [email protected]",
"email": "[email protected]"
},
"slug": "davonte-sawayn-1",
"name": "1",
"body": "Aliquam placeat veritatis alias sed et inventore. Animi animi amet recusandae qui voluptates quidem. Eos qui culpa aut molestias.",
"tags": [
{
"id": 6,
"name": "testTag"
},
{
"id": 1,
"name": "PHP"
},
{
"id": 2,
"name": "Laravel"
}
],
"time": {
"created_at": "2020-05-05T15:19:26.000000Z",
"updated_at": "2020-05-05T15:19:26.000000Z"
}
},
{
"id": 2,
"user": {
"id": 1,
"full_name": "test [email protected]",
"email": "[email protected]"
},
"slug": "lura-weimann-iii-1",
"name": "2",
"body": "Praesentium velit deserunt eaque quia consequatur dolor. Delectus nulla quasi in maiores. Et recusandae sed et magnam aperiam exercitationem dolor et.",
"tags": [
{
"id": 3,
"name": "Node"
},
{
"id": 2,
"name": "Laravel"
}
],
"time": {
"created_at": "2020-05-05T15:19:26.000000Z",
"updated_at": "2020-05-05T15:19:26.000000Z"
}
},
{
"id": 11,
"user": {
"id": 1,
"full_name": "test [email protected]",
"email": "[email protected]"
},
"slug": "raphaelle-hudson-jr-1",
"name": "3",
"body": "Maiores in ullam error odio accusantium rerum aliquam. Numquam explicabo fugiat facilis natus accusantium. Non et perferendis fugit in quas ipsum voluptate sit.",
"tags": [],
"time": {
"created_at": "2020-05-06T12:18:51.000000Z",
"updated_at": "2020-05-06T12:18:51.000000Z"
}
}
]
}
0 likes
1 reply
mastermindlegion's avatar
Level 1

hey there, problem was that I wasn't using static collection. This example works well:

        return  ArticleResource::collection(Article::with(['user', 'tags'])->paginate(3));

this doesn't work, meta is not being included:

  $collection = new ArticlesCollection(
          ArticleResource::collection(Article::with(['user', 'tags'])->paginate(3))
        );
         return $collection;

Please or to participate in this conversation.