Magento 2: Get product by SKU or ID

There are two different ways, how to get product in Magetno 2: object manager method and dependency injection. The object manager method is easier, but according to Magento 2 documentation, it is not recommended and we always should use dependency injection method. Lets begin from easier way to get this done!

Objectmanager method

The object manager method is easier way to get a product, because a code snippet is in one piece and it can be pasted almost everywhere in Magento 2 code, including .phtml templates files.

Code snippet to get product by sku

$product = \Magento\Framework\App\ObjectManager::getInstance()
    ->create(\Magento\Catalog\Model\Product::class)
    ->loadByAttribute('sku', $sku);

Code snippet to get product by id

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

Product sku and id are the most common used product identifiers, but you can use other unique product attributes to get a product.

Dependency injection method

We should use this method always when it’s possible. The example bellow is according situation when we need to get product in .phtml template, but the same, code lines (highlighted in red) can be added in model, helper, observer, plugin or controller class.

app/code/Magetrend/HelloWorld/Block/HelloBlock.php
<?php
namespace Magetrend\HelloWorld\Block;
class HelloBlock extends \Magento\Framework\View\Element\Template
{
    public $productRepository;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
        array $data = []
    ) {
        $this->productRepository = $productRepository;
        parent::__construct($context, $data);
    }

    public function getProductById($id)
    {
        return $this->productRepository->getById($id);
    }
    
    public function getProductBySky($sku)
    {
        return $this->productRepository->get($sku);
    }
}

then in .phtml template we can call it to get product by sku

<?php $product = $block->getProductBySky($productSku); ?>

or to get product by id

<?php $product = $block->getProductById($productId); ?>

Troubleshooting

No changes in frontend

If you have added the object manager code snippet in .phtml template file and can’t see any changes in fronted, probably it will be related to cache. Just simply clear it via Magento 2 admin.

Exception after added product repository class to controller constructor

There is need to run magento upgrade command via ssh because controller constructor dependencies was modified

bin/magento setup:upgrade;

Exception: The product that was requested doesn’t exist.

This error means that product ID or SKU is incorrect or product was deleted. Bellow are code snippet how to check product availability.

try {
    $product = $this->productRepository->get('NOT-EXISTING-PRODUCT');
} catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
    $product = false;
}
        
if ($product !== false) {
    //do something if product exist
}

Conclusion

Choose wisely and use dependency injection method.

That’s all for this article. All feedbacks and questions are very welcome, I will be more than happy to append this article with your case.

Happy code guys!

Leave a Comment