0

I want to fetch all products in my ecommerce and all its attributes. How can I do that? For example, I want to be able to call a function that gets all products, an then one by one fetch all the attributes of that product.

1 Answer 1

0

You can try below code for your requirement.

<?php
namespace Test\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{    
protected $_productCollectionFactory;

public function __construct(
    \Magento\Backend\Block\Template\Context $context,        
    \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,        
    array $data = []
)
{    
    $this->_productCollectionFactory = $productCollectionFactory;    
    parent::__construct($context, $data);
}

public function getProductCollection()
{
    $collection = $this->_productCollectionFactory->create();
    $collection->addAttributeToSelect('*');
    return $collection;
}
}
?>

Display in phtml using block method

$productCollection = $block->getProductCollection(); foreach ($productCollection as $product) { print_r($product->getData());
echo "<br>"; }

2
  • What if I want to fetch also all attributes that are not in the default attribute set? Will this work too?
    – dirac
    Commented Jan 28, 2019 at 14:35
  • Yes. It will fetch all attributes Commented Jan 28, 2019 at 18:34

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.