Inventory Stock in the Multi-Source (MSI) module are used for mapping a sales channel to source locations in Magento 2.
You can see a list of available Stocks from the Stores -> Inventory -> Stocks link.
You can get a list of stocks available for the system using the StockRepositoryInterface of Inventory API module.
I have created a simple Model class to get all the stocks,
<?php
namespace Jesadiya\GetStocks\Model;
use Exception;
use Psr\Log\LoggerInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\InventoryApi\Api\Data\StockInterface;
use Magento\InventoryApi\Api\StockRepositoryInterface;
class StocksList
{
/**
* @var SearchCriteriaBuilder
*/
private $searchCriteriaBuilder;
/**
* @var StockRepositoryInterface
*/
private $stockRepository;
/**
* @var LoggerInterface
*/
private $logger;
public function __construct(
SearchCriteriaBuilder $searchCriteriaBuilder,
StockRepositoryInterface $stockRepository,
LoggerInterface $logger
) {
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
$this->stockRepository = $stockRepository;
$this->logger = $logger;
}
/**
* @return StockInterface[]|null
*/
public function getStocksList()
{
$searchCriteria = $this->searchCriteriaBuilder->create();
$stockInfo = null;
try {
$stockData = $this->stockRepository->getList($searchCriteria);
if ($stockData->getTotalCount()) {
$stockInfo = $stockData->getItems();
}
} catch (Exception $exception) {
$this->logger->error($exception->getMessage());
}
return $stockInfo;
}
}
Call function to fetch a list of stocks,
$stocksList = $this->getStocksList();
if ($stocksList) {
foreach ($stockData->getItems() as $stocks) {
foreach ($stocks as $stock) {
echo $stock['stock_id']; // 1
echo $stock['name']; // Default
}
}
}
Using Inventory Stocks you can retrieve the list of stocks available in the system.
