Magento 2 get product collection with filter stock

get only in stock product in the collection

See below code

$collection =  $this->_productCollectionFactory->create();

3 Answers 3


You can get only "in stock" product in the collection using following way:



namespace Vendor\Module\Controller\Index;

use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;

class Index extends Action
     * @var CollectionFactory
    protected $collectionFactory;

     * [__construct description]
     * @param Context           $context           [description]
     * @param CollectionFactory $collectionFactory [description]
    public function __construct(
        Context $context,
        CollectionFactory $collectionFactory
    ) {
        $this->productCollection = $collectionFactory;

    public function execute()
        /*Get in stock product collection*/
        $collection = $this->productCollection->create()->addFieldToSelect('*')
            ->setFlag('has_stock_status_filter', false)
            ->joinField('stock_item', 'cataloginventory_stock_item', 'is_in_stock', 'product_id=entity_id', 'is_in_stock=1');
        echo "<pre>";

I hope it will helpful for you.


By default magento filters only in stock products in collection

// $this->productCollection is object of Magento\Catalog\Model\ResourceModel\Product\Collection
 $collection = $this->productCollection->addAttributeToSelect('*')->load();

if you want to get out of stock products in collection then use

$collection = $this->productCollection->addAttributeToSelect('*')
->setFlag('has_stock_status_filter', false)
  • no it is not working I am using "Magento\Catalog\Model\ResourceModel\Product\CollectionFactory" AND "Magento\Catalog\Model\ResourceModel\Product\Collection" get all product
    – Bharat
    Commented Feb 12, 2020 at 8:34
  • which magento version you used i tested this code in magento 2.3.3 it's working in my case Commented Feb 12, 2020 at 10:48
  • Magento version - 2.2.7 EE
    – Bharat
    Commented Feb 12, 2020 at 11:13
  • hello @bharat i am also check above code in Magento 2.3.1 EE and its working also check in Magento 2.2.7. $collection = $this->productCollection->addAttributeToSelect('*')->load(); this gives only in stock product collection Commented Feb 12, 2020 at 11:46

You Can also try like this for Better Understandably and Readability:-


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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