Question

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);

No correct solution

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top