Create a block class to your custom module named Vendor_Module to below path:
app/code/Vendor/Module/Block/Product.php
and add the below content to it:
<?php
namespace Vendor\Module\Block;
class Product extends \Magento\Framework\View\Element\Template
{
protected $_scopeConfig;
protected $_stockInterface;
protected $_productRepository;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Magento\CatalogInventory\Api\StockStateInterface $stockInterface,
\Magento\Catalog\Model\ProductRepository $productRepository
){
$this->_scopeConfig = $scopeConfig;
$this->_stockInterface = $stockInterface;
$this->_productRepository = $productRepository;
parent::__construct($context);
}
public function getStockMessage($productId){
$_product = $this->getProductById($productId);
$_stock = $this->getStock($_product);
if($_stock <= $this->getThresoldQty()){
return __('Only %1 left', $_stock);
}
return '';
}
public function getProductById($id)
{
return $this->_productRepository->getById($id);
}
public function getStock($_product)
{
return $this->_stockInterface->getStockQty($_product->getId(), $_product->getStore()->getWebsiteId());
}
public function getThresoldQty(){
return $this->_scopeConfig->getValue('cataloginventory/options/stock_threshold_qty', \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
}
}
Now add the below code to top of your list.phtml
$blockObj = $block->getLayout()->createBlock('Vendor\Module\Block\Product');
Then call the below block inside your foreach loop:
<?php echo $blockObj->getStockMessage($_product->getId()); ?>
You can use the thing in your product details page.