Skip to main content
4 of 4
Removed semicolon that broke syntax

You need to apply joinField to get instock items only:

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