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:
- First, fetch the paginated data.
- Then, iterate over the paginated data to append the additional data.
- 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.