I want to get the First item from the collection so I have used following code. But it gives some warning on the usage of getFirstItem()

protected $_sampleFactory;

public function __construct(
   \Vendor\Module\Model\sampleFactory $sampleFactory,
) {
   $this->_sampleFactory = $sampleFactory;
public function execute()
   $collection = $this->_sampleFactory->create()->getCollection()->addFieldToFilter("product_id", $product_id);

   $customer_id = $collection->getFirstItem()->getCustomerId();
   return $customer_id;

This code is working properly but when I checked with magento-coding-standard tool its given me the warning on usage of getFirstItem() as follow.

107 | WARNING | Data load getFirstItem() method detected in loop
107 | WARNING | getFirstItem does not limit the result of collection load to one item.

Anyone has any idea how to solve it?


1 Answer 1


If you want only 1 Item from collection then you can limit the collection by using, $collection->setPageSize(1) and $collection->setCurPage(1) so It will fetch only 1 value from your collection. In your case you can do it like,

   $collection = $this->_sampleFactory->create()->getCollection()
                 ->addFieldToFilter("product_id", $product_id)
  • You still may receive that standard violation error, but as long as you setPageSize(1), then you should be okay.
    – df2k2
    Apr 18, 2018 at 18:07
  • I don't think so still It will gives the error after setting this @df2k2
    – Keyur Shah
    Apr 18, 2018 at 18:17
  • 1
    Thanks for the reply, I'll have to double-check that then. Perhaps I have something missing or a setting incorrect. I do agree with your answer as the correct answer, though.
    – df2k2
    Apr 18, 2018 at 18:24
  • Your code is working but you have used getFirstItem() in your code.So MEQP gives me again same warning.Anyone has other solution then please upload. Apr 19, 2018 at 13:39
  • @EmiproTechnologiesPvt.Ltd did you find any solution regarding it.
    – Himanshu
    Dec 20, 2018 at 9:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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