ignaciodev's avatar

Issue using resources and pagination

I am fetching from my db like this:

$shops = ShopifyShop::listable()->cursorPaginate(2);

If I return this, everything works well:

return ShopifyShopIndexResource::collection($shops);

However, I need to append some data to each item in the collection, which I'm trying to do like this:

return ShopifyShopIndexResource::collection(
    $shops->map(fn ($shop) => (new ShopifyShopIndexResource(
        resource: $shop,
        products: $this->shopifyService->getTopProductsFromCache($shop),
    )))
);

Works great, except for the fact that I loose all my pagination data?

0 likes
2 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

The issue you're encountering is due to the fact that when you map over the collection and create new instances of ShopifyShopIndexResource, you lose the pagination metadata that comes with the original cursorPaginate result.

To solve this, you can manually append the additional data to each item in the collection without losing the pagination metadata. Here's how you can do it:

  1. First, fetch the paginated data.
  2. Then, iterate over the paginated data to append the additional data.
  3. Finally, return the modified collection while preserving the pagination metadata.

Here's a revised version of your code:

$shops = ShopifyShop::listable()->cursorPaginate(2);

$shops->getCollection()->transform(function ($shop) {
    return new ShopifyShopIndexResource(
        resource: $shop,
        products: $this->shopifyService->getTopProductsFromCache($shop),
    );
});

return ShopifyShopIndexResource::collection($shops);

In this solution:

  • cursorPaginate(2) fetches the paginated data.
  • getCollection()->transform(...) iterates over the collection and transforms each item, appending the additional data.
  • ShopifyShopIndexResource::collection($shops) returns the modified collection with the pagination metadata intact.

This way, you can append the additional data to each item in the collection without losing the pagination information.

1 like

Please or to participate in this conversation.