How to load product by SKU in magento 2
The correct way, according to Magento 2 service contracts, is using repositories:
$product = $this->productRepositoryInterface->get($sku);
Use Magento\Catalog\Api\ProductRepositoryInterface
to get it in your constructor.
Full example:
...
private $productRepository;
...
public function __construct(
...
\Magento\Catalog\Api\ProductRepositoryInterface $productRepository
...
) {
...
$this->productRepository = $productRepository;
...
}
public function loadMyProduct($sku)
{
return $this->productRepository->get($sku);
}
...
Note:
If the product does not exists, this method triggers a NoSuchEntityException
error as it would be in the best Magento2 practice.
So, if you need to handle somehow, wrap it in a try/catch block.
Instead of using the object manager directly, inject the ProductFactory:
public function __construct(\Magento\Catalog\Model\ProductFactory $productFactory)
{
$this->productFactory = $productFactory;
}
Then use it like this:
$product = $this->productFactory->create();
$product->loadByAttribute('sku', $sku);
or to do a full load (the above loads it using a collection):
$product = $this->productFactory->create();
$product->load($product->getIdBySku($sku));
I like @phoenix128-riccardot 's answer, but would add an exception, just in case the product does not exist:
try { $product = $this->productRepositoryInterface->get($sku); } catch (\Magento\Framework\Exception\NoSuchEntityException $e){ // insert your error handling here }
I was not able to add it as a comment (too low reputation), sorry.