I try to access stock data for a product, using


and receive the following error on this line

PHP Fatal error: Call to a member function getIsInStock() on null.

Obviously the stock_item extension attribute was not loaded. $product comes from the product repository and has been loaded with $productRepository->getList().

How can I get products with stock information from the product repository?

2 Answers 2


Apparently this is not possible in a reasonable way as of Magento 2.1

You can use the stock registry and pass each item of the result to Magento\CatalogInventory\Helper\Stock::assignStatusToProduct().

But this results in a single database query for each product. In my tests with 2000 products, this takes three times longer than loading the collection directly with Magento\CatalogInventory\Model\ResourceModel\Stock\Status::addStockDataToCollection()

To optimize the stock registry, one would have to add a method to fetch multiple stock items at once and assign them to an array of products.


If you have access to the productRepository you can do this:


  • But this will trigger another full product load, right? The repository methods are slow enough already, triggering the classic "load in a a loop" is not an option for me. Commented Aug 2, 2016 at 21:00
  • 1
    Correct. You can't call isInStock() on the items, since they'll always return 1, even if they're not in stock and you also can't use getStockData() since that'll return NULL. As far as I know stock data isn't included in the product list items.
    – Ruud N.
    Commented Aug 2, 2016 at 21:10
  • Thanks, I'll probably resort to collections again for more flexibility Commented Aug 2, 2016 at 21:13
  • Alternatively you can use the \Magento\CatalogInventory\Api\StockItemRepositoryInterface to just load the stock item seperately, like this: $this->_stockItemRepository->get($product->getQuantityAndStockStatus())->getIsInStock()
    – Ruud N.
    Commented Aug 2, 2016 at 21:51
  • 3
    where i can find method getQuantityAndStockStatus define?
    – mrtuvn
    Commented Aug 4, 2016 at 3:31

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.