Monday, February 13, 2017

Get product stock information programmatically in Magento 2

Get product stock information programmatically in Magento 2

<?php
use \Magento\Framework\App\Bootstrap;

#require __DIR__ . '/../app/bootstrap.php';
require '/www/mag2.local/app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();

### Setting area code
### NOTE: for more info http://devdocs.magento.com/guides/v2.1/architecture/archi_perspectives/components/modules/mod_and_areas.html
$state = $objectManager->get('\Magento\Framework\App\State');
#$state->setAreaCode('base');

$stockItemRepository = $objectManager->get('\Magento\CatalogInventory\Model\Stock\StockItemRepository');

$productId = 1;

$productStock = $stockItemRepository->get($productId);

echo 'Qty: ' . $productStock->getQty() . PHP_EOL;
echo 'getMinQty: ' . $productStock->getMinQty() . PHP_EOL;
echo 'getMinSaleQty: ' . $productStock->getMinSaleQty() . PHP_EOL;
echo 'getMaxSaleQty: ' . $productStock->getMaxSaleQty() . PHP_EOL;
echo 'getIsInStock: ' . $productStock->getIsInStock() . PHP_EOL;

No comments: