I have a function which return the array of resource and collection
/**
*
* get the brand
*
* @param Brand $brand
* @return JsonResponse
*/
public function show(Brand $brand) {
$brand = QueryBuilder::for(Brand::class)
->with([
'products'
])
->find($brand->id);
$products = QueryBuilder::for(Product::class)->with(['brand', 'registrant', 'productType', 'director', 'publisher'])
->where('brand_id', $brand->id)
->paginate(12, ['*'], 'product_page');
// return new ProductCollection($products);
return response()->json([
'data' => [
'brand' => new BrandResource($brand),
'products' => new ProductCollection($products)
]
]);
}
If I run this then the products have only 12 records but there is 3K+ records when I uncomment the ProductCollection and comment the response underneath or more I just return the collection without wrapping in an Array it contains the pagination.
For a collection (different from an eloquent collection) you can use a lengthaware paginator
and slice. But best to let the database and sql do the work here. Too large of a array it's not good
to paginate.
@muhammadsaim Try paginating this query in non api code, not json, in a foreach, does it paginate correctly?
It has to know the next offset for paginating. I suggest also a toSql() to see the actual sql used.
You can try a length aware paginator as well.
Also throw in a page number and see what happens. I normally handle pagination in the javascript
and use skip and take so the next run will know the offset.