0

Does anyone know how to get StockItem by product_id in Magento 2.4.x? We have the following code that works most of the time, but sometimes it throws the following error: "The stock item with the "12399" ID wasn't found. Verify the ID and try again."

class AbstractTemplate extends \Magento\Framework\View\Element\Template
{

 protected $_stockItemRepository;

 public function __construct(

     \Magento\CatalogInventory\Model\Stock\StockItemRepository $stockItemRepository, 
             array $data = array()
 ) {

     $this->_stockItemRepository = $stockItemRepository;

   }

 public function getStockItem($productId)
     {
     return $this->_stockItemRepository->get($productId);
 }
}

then we do:

$product = $this->_productFactory->create()->load($item->getId());
$stock_quantity = $this->getStockItem($item->getId());

$product_quantity = $this->or_else($stock_quantity->getQty(), 0);

1 Answer 1

0

You can try with StockRegistryInterface Like this:

Code with dependency Indection:

class Index extends \Magento\Framework\View\Element\Template
{

    protected $_stockRegistryInterface;

    public function __construct(
        \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistryInterface, 
        array $data = array()
    ) {

        $this->_stockRegistryInterface = $stockRegistryInterface;
    }

    public function getStockItem($productId)
    {
        return $this->_stockRegistryInterface->getStockItem($productId);
    }
}

For testing, you can check with objectmanager:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$stockRegistry = $objectManager->get('Magento\CatalogInventory\Api\StockRegistryInterface');
$stockItem=$stockRegistry->getStockItem($_product->getId());

Note: Must use code with dependency Injection.

1
  • No, can't use this. StockRegistryInterface has been deprecated in Magento 2.4
    – Kevin M
    May 12, 2021 at 6:46

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.