Magento – How to check the product image is available or not in magento 2

magento2productproduct-images

I am getting my product collection like this.to show i n a slider in home page.

public function getProductCollection($categoryId,$filter_attribute)
{   

    $category = $this->_categoryFactory->create()->load($categoryId);
    $collection = $this->_productCollectionFactory->create();
    $collection->addAttributeToSelect('*');
    $collection->addAttributeToFilter($filter_attribute, 1);

    $collection->addCategoryFilter($category);
    $collection->addAttributeToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);
    $collection->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
    return $collection;
}

I can get the products from this in my slider.
I want to call place holder image if the product haven't updated with any image.

I tried this way.

$image_have =  strcmp($product->getImage(),'no_selection');
if($image_have != 0){
    $productImageUrl = $productImageUrl;//this is image url
}else{
    $productImageUrl = $PlaceholderImage;//this is place holder image url
}

If i add a product without uploading product image the place holder image is not showing.
Some time $product->getImage() this return empty. Is there any way to check the product has an image or not.

Best Answer

Please follow below steps:

Step-1: Extent your custom Block class from Magento\Catalog\Block\Product\ListProduct

Step-2: Use below code for display image in your template

$image = 'category_page_grid'; or use $image = 'category_page_list';

in foreach loop use below code to display image

<?php $productImage = $block->getImage($_product, $image); ?>
<?php // Product Image ?>
<a href="<?php /* @escapeNotVerified */ echo $_product->getProductUrl() ?>" class="product photo product-item-photo" tabindex="-1">
    <?php echo $productImage->toHtml(); ?>
</a>

Otherwise Study the code of below files..

  • Magento\Catalog\Block\Product\ListProduct.php
  • vendor\magento\module-catalog\view\frontend\templates\product\list.phtml

Hope this help....!