2

In Magento 2 there is more than one method to get product by id. Anyone show me how to get product y in any of the method step by step include files name nd path used.

5 Answers 5

4
  1. Inject Magento\Catalog\Api\ProductRepositoryInterface in your constructor and assign it to a variable in the class.
 $this->productRepository = $productRepository;
  1. Get the product by it's SKU -
 $product = $this->productRepository->get($productSku);
  1. Get the product by it's ID -
$product = $this->productRepository->getById($id);

This is the recommended way to access a data from database in Magento.

1

Add block and Controller file like this

protected $_productloader;

public function __construct(
    ........................................
    \Magento\Catalog\Model\ProductFactory $_productloader,
    ........................................
) {
    ........................................
    $this->_productloader = $_productloader;
    ........................................
}
public function getLoadProduct($id)
{
    return $this->_productloader->create()->load($id);
}

In controler and block you can call using

$product_id = 45;
$data = $this->getLoadProduct($product_id);
print_r($data->getData());

In phtml file call

$product_id = 45;
$data = $block->getLoadProduct($product_id);
print_r($data->getData());

block and phtml link like this (add your block file path )

<block class="VendoreName\ModuleName\Block\YourBlockName" name="prd.data" template="VendoreName_ModuleName::yourfilname.phtml" >
0

Object method

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($product_id);

Factory Method

<?php
namespace Test\Module\Block;

class Product extends \Magento\Framework\View\Element\Template
{

  protected $_productloader;  


  public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Model\ProductFactory $_productloader

    ) {


        $this->_productloader = $_productloader;
        parent::__construct($context);
    }
    public function getLoadProduct($id)
    {
        return $this->_productloader->create()->load($id);
    }

}

phtml file code

$product=$this->getLoadProduct(20);
echo $product->getName();


<?php
    namespace Test\Module\Block;
    use Magento\Catalog\Api\ProductRepositoryInterface;
    class Product extends \Magento\Framework\View\Element\Template
     {
          protected $productRepository; 
          protected $_storeManager; 

          public function __construct(
            \Magento\Framework\App\Action\Context $context,
            ProductRepositoryInterface $productRepository
          ) {
              parent::__construct($context);

              $this->productRepository = $productRepository;
          }
          public function getProduct()
          {

              $productId=1;
              return $product = $this->productRepository->getById($productId);
          }
      }
0

Here I used the easiest way to get the ProductName by ID.

use this code in your Controller <vendor name>/<module>/Controller/Index/Index.php


<?php
namespace <vendor name>\<module>\Controller\Index;
use Magento\Catalog\Model\Product;
use Magento\Framework\App\Action\Context;

class Index extends \Magento\Framework\App\Action\Action
{
 protected $_pageFactory,$productId=731,$productModel;
 public function __construct(Context $context,Product $productModel)
{
 parent::__construct($context);
 $this->productModel = $productModel;
 $this->getProductModel();
}
 public function execute()
{
 return $this->_pageFactory->create();
}
 public function getProductModel()
{
 $product=$this->productModel->load($this->productId);
 echo $product->getName();
 }
}

0
<?php

declare(strict_types=1);
namespace Vendor\Module\ViewModel;

use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\ProductFactory;
use Magento\Catalog\Model\ResourceModel\Product\Collection;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Directory\Model\CurrencyFactory;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Registry;
use Magento\Store\Model\StoreManagerInterface;

class Index implements 
  \Magento\Framework\View\Element\Block\ArgumentInterface
{
    /**
     * @var ProductFactory
     */
    private $productFactory;

    /**
     * @var ProductRepositoryInterface
     */
    private $productRepository;

    /**
     * @var StoreManagerInterface
     */
    private $storeManager;

    /**
     * @var Registry
     */
    private $registry;

    /**
     * @var CurrencyFactory
     */
    private $currencyFactory;

    /**
     * @var CollectionFactory
     */
    private $collectionProductFactory;

    /**
     * @param ProductFactory $productFactory
     * @param ProductRepositoryInterface $productRepository
     * @param StoreManagerInterface $storeManager
     * @param Registry $registry
     * @param CurrencyFactory $currencyFactory
     * @param CollectionFactory $collectionProductFactory
     */
    public function __construct(
       ProductFactory $productFactory,
       ProductRepositoryInterface $productRepository,
       StoreManagerInterface $storeManager,
       Registry $registry,
       CurrencyFactory $currencyFactory,
       CollectionFactory $collectionProductFactory

    ){
        $this->productFactory = $productFactory;
        $this->productRepository = $productRepository;
        $this->storeManager = $storeManager;
        $this->registry = $registry;
        $this->currencyFactory = $currencyFactory;
        $this->collectionProductFactory = $collectionProductFactory;
    }

    /**
     * @param $id
     * @return Product
     */
    public function loadProduct($id)
    {
        return $this->productFactory->create()->load($id);
    }

    /**
     * @return ProductInterface
     * @throws NoSuchEntityException
     */
    public function getProductId($productId)
    {
        return $this->productRepository->getById($productId);
    }

    /**
     * @return int
     * @throws NoSuchEntityException
     */
    public function getStoreId()
    {
        return $this->storeManager->getStore()->getId();
    }

    /**
     * @return mixed
     */
    public function getCurrentProduct()
    {
        return $this->registry->registry('current_product');
    }

    /**
     * @return Collection
     */
    public function getProductCollection(){

        $productCollection = $this->collectionProductFactory->create();
        $productCollection->addAttributeToSelect('*');
        $productCollection->load();
        return $productCollection;
    }

}

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.