Product and stock information

Home / Magento 2 / Product and stock information

Recently I was looking for information on how to retrieve stock information of a product. I read many different answers on Stack Overflow and blogs, but none worked with Magento 2.1.4. After getting my head down to reading core, I realised people was using the product id instead of the stock id. This probably works in many cases, but not in mine since the products entity_id wasn’t the same as the stock’s item_id.

This is how to retrieve the stock item the correct way (as far as I know) using product ID. I’m aware of that Magento has fields in the table cataloginventory_stock_item for “stock_id” and “website_id” and that’s not taken in consideration in the code below. But since Magento 1 the fields always been there but not implemented but Magento.

<?php

namespace Codepeak\Example\Model;

use \Magento\CatalogInventory\Model\Stock\Item;

class Mymodel
{
    /**
     * @var Item
     */
    protected $stockItem;

    /**
     * Mymodel constructor.
     *
     * @param Item $stockItem
     */
    public function __construct(Item $stockItem)
    {
        $this->stockItem = $stockItem;
    }

    /**
     * Fetch the stock item by using product model
     *
     * @param $productModel
     */
    public function getStockItemByProduct($productModel)
    {
        try {
            $stockItem = $this->stockItem->load(
                $productModel->getId(),
                'product_id' // Field name in table cataloginventory_stock_item
            );

            return $stockItem;
        } catch (\Exception $e) {
            echo 'Something went wrong and was not handled: ' . $e->getMessage();
            exit;
        }
    }
}