Magento – How to filter related product collection by is_salable magento 2

magento-2.1.8product-collectionrelated-products

Related products are showing with out of stock products, I want to hide out of stock products from related products only.

$this->_itemCollection = $product->getRelatedProductCollection()
    ->addAttributeToSelect('required_options')
    ->setPositionOrder()
    ->addStoreFilter();

I have found above code to get related product collection. How can I filter this collection by is_salable?

Best Answer

Have you tried something like this? https://magento.stackexchange.com/a/130070/3566

Not sure if this could be achieved with a plugin approach, setting a aroundGetItems plugin, after would not be an option, as collection is loaded in _prepareData() method

/**
 * @return $this
 */
protected function _prepareData()
{
    $product = $this->_coreRegistry->registry('product');
    /* @var $product \Magento\Catalog\Model\Product */

    $this->_itemCollection = $product->getRelatedProductCollection()->addAttributeToSelect(
        'required_options'
    )->setPositionOrder()->addStoreFilter();

    if ($this->moduleManager->isEnabled('Magento_Checkout')) {
        $this->_addProductAttributesAndPrices($this->_itemCollection);
    }
    $this->_itemCollection->setVisibility($this->_catalogProductVisibility->getVisibleInCatalogIds());

    $this->_itemCollection->load();

    foreach ($this->_itemCollection as $product) {
        $product->setDoNotUseCategoryId(true);
    }

    return $this;
}

So, I'd rewrite Magento\Catalog\Block\Product\ProductList\Related & use addInStockFilterToCollection(), as explained in the quoted answer