Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ResourceCollection doesn't include pagination links

CommentsCollection

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))];
}

Response

"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"
            }
        ]
    }

This happens when resource with use of ::collection method or even ResourceCollection returned as a part of the array.

If we're going to remove array and return pure collection:

return new CommentsCollection(Comment::paginate(1))

everything is going to work fine and response will include meta and links.

Why does API Resource (using collection method or ResourceCollection) doesn't include pagination information when returned in array?

like image 371
Src Avatar asked Mar 14 '18 23:03

Src


2 Answers

i have encountered this problem and found a solution check the following link for a detailed description of the solution

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

in short check the following code snippet that solve the problem

$data = SampleModel::paginate(10);
return ['key' => SampleModelResource::collection($data)->response()->getData(true)];
like image 157
Mahmoud Avatar answered Sep 30 '22 18:09

Mahmoud


I notice result of resource collection must return individually to work correctly

return ItemMiniResource::collection(
        $items->paginate(10)
    );

It's works perfectly, but

$data['items'] = ItemMiniResource::collection(
        $items->paginate(10)
    );
return $data

not include paginate links

like image 34
Mahdi Majidzadeh Avatar answered Sep 30 '22 16:09

Mahdi Majidzadeh