5

How to load the model in magento 2 like

Mage::getModel('catalog/product')->load() 

as we used to get in magento 1.

2 Answers 2

25

It is recommended to use dependency injection rather than directly using object Manager. Example: In your block file you can use following code to return product collection:

public function __construct( \Magento\Framework\View\Element\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(); return $collection; } 
Sign up to request clarification or add additional context in comments.

3 Comments

This is the correct approach using dependency injection. +1
Hi @Manashvi, i wants to fecth these product/cache/1d4ec593232a3f40f7a929d5b10820a2/u/g/ug03-bk-0.jpg images
@shivashankarm first of all, why? it's in cache, if you ever clear cache then the URL has changed and so has everything else. I suspect you've figured this by now but you shouldnt ever be referencing images stored in cache
22

Try this for get all product collection

<?php $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory'); $collection = $productCollection->create() ->addAttributeToSelect('*') ->load(); foreach ($collection as $product){ echo 'Name = '.$product->getName().'<br>'; } ?> 

2 Comments

<?php $productId = 8; $objectManager = \Magento\Framework \App\ObjectManager::getInstance(); $currentproduct = $objectManager->create('Magento\Catalog\Model\Product')->load($productId); echo $currentproduct->getName(); ?>
It returns []. Why ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.