I want to retrieve all the products. But would like to limit it to say 100 at a time to avoid too much memory usage.

I have the collection factory injected in the constructor as

\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $pfac

Using $pfac, created a collection.

$collection = $this->pfac->create();
$pageCount = $collection->getLastPageNumber();

Now, I thought I could just iterate one page at a time using setCurPage, but alas, only the first page data is present always.

I tried:

for($x = 1; $x <= $pageCount; $x++) {
     $pageData = $collection->getData();

But the $pageData is always the same (first page data).

I tried calling $collection->load(), thinking that might be needed, but again, not helpful.


once a collection is loaded (or iterated, which calls load) you cannot change its paging and filters anymore. I mean, you can, but you will still get the same results as first time.

So you need different collections.

$pageCount = $this->pfac->create()->setPageSize(100)->getLastPageNumber();
for($x = 1; $x <= $pageCount; $x++) {
    $collection = $this->pfac->create();
    $pageData = $collection->getData();
  • in "for loop" objection creating bad, so much every time when "for loop" go through new object creation. – Padhiyar Gaurang Sep 3 at 9:15
  • could be, but it's better if you need to perform other operations on the collection. Otherwise a collection clone is possible. – Marius Sep 3 at 11:41
 $pagesize = 100;
 $pageCurrent = 1;
 $pageoffset = ($pageCurrent - 1) * $pagesize;

 $collection = array_slice($collection, $pageoffset, $pageoffset + $pagesize);
  • this will still load the full collection in memory. – Marius Sep 3 at 5:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.