Magento 2 – Fix ‘Call to a Member Function getIsInStock() on Null’ Error

magento-2.1magento2productservice-contractstock

I try to access stock data for a product, using

$product->getExtensionAttributes()->getStockItem()->getIsInStock()

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?

Best Answer

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.