Skip to main content
3 of 4
added 114 characters in body
Rohan Hapani
  • 17.5k
  • 9
  • 55
  • 96

You need to apply joinField for get only instock items :

Method 1 :

$category = $this->categoryFactory->create()->load($categoryId); 
$categoryProducts = $category->getProductCollection()
                         ->addAttributeToSelect('*')
                         ->addAttributeToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
                         ->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
                         ->addAttributeToFilter('type_id',\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE);
                         ->joinField('stock_item', 'cataloginventory_stock_item', 'is_in_stock', 'product_id=entity_id', 'is_in_stock=1')
                         ->setPageSize(6);

Method 2 :

$category = $this->categoryFactory->create()->load($categoryId); 
$categoryProducts = $category->getProductCollection()
                         ->addAttributeToSelect('*')
                         ->addAttributeToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
                         ->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
                         ->addAttributeToFilter('type_id',\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE);    
                         ->addAttributeToFilter('is_in_stock', 1)
                         ->setPageSize(6);
Rohan Hapani
  • 17.5k
  • 9
  • 55
  • 96