{"id":205,"date":"2019-06-07T12:24:53","date_gmt":"2019-06-07T12:24:53","guid":{"rendered":"https:\/\/www.magetrend.com\/blog\/?p=205"},"modified":"2022-05-29T08:40:09","modified_gmt":"2022-05-29T08:40:09","slug":"magento-2-get-product-by-sku-or-id","status":"publish","type":"post","link":"https:\/\/www.magetrend.com\/blog\/magento-2-get-product-by-sku-or-id\/","title":{"rendered":"Magento 2: Get product by SKU or ID"},"content":{"rendered":"\n<p>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 <a rel=\"noreferrer noopener\" aria-label=\"Magento 2 documentation (opens in a new tab)\" href=\"https:\/\/devdocs.magento.com\/guides\/v2.3\/extension-dev-guide\/object-manager.html\" target=\"_blank\">Magento 2 documentation<\/a>, it is not recommended and we always should use dependency injection method. Lets begin from easier way to get this done!<\/p>\n\n\n<div class=\"simple-container\"> <a class=\"simple-img\" href=\"https:\/\/www.magetrend.com\/magento-2-pdf-invoice?utm_source=article&utm_medium=post_205&utm_campaign=pos1\"><img decoding=\"async\"  src=\"\/blog\/wp-content\/uploads\/prod\/magento-2-pdf-templates.png\" \/><\/a> <div class=\"simple-row simple-title\"><a href=\"https:\/\/www.magetrend.com\/magento-2-pdf-invoice?utm_source=article&utm_medium=post_205&utm_campaign=pos1\">The Most Popular PDF Designer for Magento 2<\/a><\/div> <div class=\"simple-row simple-text\"><a href=\"https:\/\/www.magetrend.com\/magento-2-pdf-invoice?utm_source=article&utm_medium=post_205&utm_campaign=pos1\">with user-friendly PDF editor to build your own PDF look<\/a><\/div> <div class=\"simple-action\"><a href=\"https:\/\/www.magetrend.com\/magento-2-pdf-invoice?utm_source=article&utm_medium=post_205&utm_campaign=pos1\">Read More<\/a> <\/div> <\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Objectmanager method<\/h2>\n\n\n\n<p>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. <\/p>\n\n\n\n<p><strong>Code snippet to get product by sku<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$product = \\Magento\\Framework\\App\\ObjectManager::getInstance()\n    -&gt;create(\\Magento\\Catalog\\Model\\Product::class)\n    -&gt;loadByAttribute('sku', <span class=\"highlight\">$sku<\/span>);<\/code><\/pre>\n\n\n\n<p><strong>Code snippet to get product by id<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$product = \\Magento\\Framework\\App\\ObjectManager::getInstance()\n    -&gt;create(\\Magento\\Catalog\\Model\\Product::class)\n    -&gt;load(<span class=\"highlight\">$id<\/span>);<\/code><\/pre>\n\n\n\n<p>Product sku and id are the most common used product identifiers, but you can use other unique product attributes to get a product. <\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Dependency injection method<\/h2>\n\n\n\n<p>We should use this method always when it&#8217;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.<\/p>\n\n\n<div class=\"file-path\"><span>app\/code\/Magetrend\/HelloWorld\/Block\/HelloBlock.php<\/span><\/div>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;?php\nnamespace Magetrend\\HelloWorld\\Block;\nclass HelloBlock extends \\Magento\\Framework\\View\\Element\\Template\n{\n    <span class=\"highlight\">public $productRepository;<\/span>\n\n    public function __construct(\n        \\Magento\\Framework\\View\\Element\\Template\\Context $context,\n        <span class=\"highlight\">\\Magento\\Catalog\\Api\\ProductRepositoryInterface $productRepository,<\/span>\n        array $data = []\n    ) {\n        <span class=\"highlight\">$this-&gt;productRepository = $productRepository;<\/span>\n        parent::__construct($context, $data);\n    }\n\n    public function getProductById($id)\n    {\n        return <span class=\"highlight\">$this-&gt;productRepository-&gt;getById($id);<\/span>\n    }\n    \n    public function getProductBySky($sku)\n    {\n        return <span class=\"highlight\">$this-&gt;productRepository-&gt;get($sku);<\/span>\n    }\n}<\/code><\/pre>\n\n\n\n<p>then in .phtml template we can call it <strong>to get product by sku<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;?php $product = $block-&gt;getProductBySky(<span class=\"highlight\">$productSku<\/span>); ?&gt;<\/code><\/pre>\n\n\n\n<p><strong>or to get product by id<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;?php $product = $block-&gt;getProductById(<span class=\"highlight\">$productId<\/span>); ?&gt;<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Troubleshooting<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">No changes in frontend<\/h3>\n\n\n\n<p>If you have added the object manager code snippet in .phtml template file and can\u2019t see any changes in fronted, probably it will be related to cache.  Just simply clear it via Magento 2 admin.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exception after added product repository class to controller constructor<\/h3>\n\n\n\n<p>There is need to run magento upgrade command via ssh because controller constructor dependencies was modified<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>bin\/magento setup:upgrade;<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Exception: The product that was requested doesn&#8217;t exist.<\/h3>\n\n\n\n<p>This error means that product ID or SKU is incorrect or product was deleted. Bellow are code snippet how to check product availability.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>try {\n    $product = $this-&gt;productRepository-&gt;get('NOT-EXISTING-PRODUCT');\n} catch (\\Magento\\Framework\\Exception\\NoSuchEntityException $e) {\n    $product = false;\n}\n        \nif ($product !== false) {\n    \/\/do something if product exist\n}<\/code><\/pre>\n\n\n\n<div style=\"height:50px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>Choose wisely and use dependency injection method.<\/p>\n\n\n\n<p>That&#8217;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.<\/p>\n\n\n\n<p>Happy code guys!<\/p>\n\n\n<div class=\"simple-container\"> <a class=\"simple-img\" href=\"https:\/\/www.magetrend.com\/magento-2-email-templates?utm_source=article&utm_medium=post_205&utm_campaign=pos2\"><img decoding=\"async\" src=\"\/blog\/wp-content\/uploads\/prod\/magento-2-email-templates.png\" \/><\/a> <div class=\"simple-row simple-title\"><a href=\"https:\/\/www.magetrend.com\/magento-2-email-templates?utm_source=article&utm_medium=post_205&utm_campaign=pos2\">Responsive Emails Templates for Magento 2<\/a><\/div> <div class=\"simple-row simple-text\"><a href=\"https:\/\/www.magetrend.com\/magento-2-email-templates?utm_source=article&utm_medium=post_205&utm_campaign=pos2\">Our #1 bestseller. With user-friendly template editor!<\/a><\/div> <div class=\"simple-action\"><a href=\"https:\/\/www.magetrend.com\/magento-2-email-templates?utm_source=article&utm_medium=post_205&utm_campaign=pos2\">Read More<\/a> <\/div> <\/div>\n","protected":false},"excerpt":{"rendered":"<p>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, &hellip; <\/p>\n<div class=\"grid-footer\"><a href=\"https:\/\/www.magetrend.com\/blog\/magento-2-get-product-by-sku-or-id\/\" class=\"more-link\">Read More <i class=\"mticon-arrow\"><\/i><\/a><\/div>\n","protected":false},"author":1,"featured_media":278,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[19,21,22,20],"_links":{"self":[{"href":"https:\/\/www.magetrend.com\/blog\/wp-json\/wp\/v2\/posts\/205"}],"collection":[{"href":"https:\/\/www.magetrend.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.magetrend.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.magetrend.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.magetrend.com\/blog\/wp-json\/wp\/v2\/comments?post=205"}],"version-history":[{"count":12,"href":"https:\/\/www.magetrend.com\/blog\/wp-json\/wp\/v2\/posts\/205\/revisions"}],"predecessor-version":[{"id":476,"href":"https:\/\/www.magetrend.com\/blog\/wp-json\/wp\/v2\/posts\/205\/revisions\/476"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.magetrend.com\/blog\/wp-json\/wp\/v2\/media\/278"}],"wp:attachment":[{"href":"https:\/\/www.magetrend.com\/blog\/wp-json\/wp\/v2\/media?parent=205"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.magetrend.com\/blog\/wp-json\/wp\/v2\/categories?post=205"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.magetrend.com\/blog\/wp-json\/wp\/v2\/tags?post=205"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}