I have all product collection but I want it sort/order_by by Stock Status.for out-of-stock.


Use below code to your class to filter out of stock product

 * @var \Magento\CatalogInventory\Helper\Stock
protected $_stockFilter;
protected $collectionFactory;

on class constructor

 public function __construct(
     \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $collectionFactory,
     \Magento\CatalogInventory\Helper\Stock $stockFilter
) {
     $this->collectionFactory = $collectionFactory;
     $this->_stockFilter = $stockFilter;

in your method add the following code

public function getProducts(){
 $collection= $this->collectionFactory->create();

here $collection is product collection.


You can use this method :- \Magento\CatalogInventory\Helper\Stock::addInStockFilterToCollection like below.


$collection = $this->productCollectionFactory->create();
$collection = $this->_addProductAttributesAndPrices($collection);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.