Steps to Retrieve Magento Get Product By SKU In Magento 2

Steps to Retrieve Magento Get Product By SKU In Magento 2

Need to streamline your product management? Magento Get Product By SKU allows you to access specific product details efficiently through a unique stock-keeping unit (SKU). This tutorial will explain how to use the Magento 2 platform to fetch product information using SKU.

Key Takeaways

  • Why Retrieving Products by SKU is Important in Magento 2?

  • Methods to Get a Product by SKU in Magento 2

  • How to get product by SKU in Magento 2?

  • How to Retrieve a Product by SKU via the Magento 2 API?

  • Best Practices for Managing SKUs and Getting Products in Magento 2

Why Retrieving Products by SKU is Important in Magento 2?

In Magento 2, retrieving products by Stock Keeping Unit (SKU) is a key operation.

SKUs are unique identifiers for products. They are important for inventory management and order processing. This function allows developers to access product information efficiently.

Unlike product names or descriptions, SKUs are unique to each product variant. For example, a red t-shirt in size medium might have the SKU "TSH-RED-M." The same shirt in large size could be "TSH-RED-L." This granularity allows for precise inventory tracking and order fulfillment.

When processing orders or updating inventory, using SKUs is faster and less error-prone. It is an advantage over using product names or descriptions. This efficiency is particularly valuable in large-scale operations. In such operations, thousands of products are managed daily.

SKUs facilitate seamless integration between different systems. These systems include inventory management, order processing, and warehouse management. This interoperability is necessary for maintaining data consistency across the entire e-commerce operation.

2 Methods to Get a Product by SKU in Magento 2

Methos 1: Dependency Injection Method

It is the recommended approach in Magento 2. It involves injecting the ProductRepository class in the constructor of your block or controller.

Code snippet:

namespace Vendor\\Module\\Block;

use Magento\\Catalog\\Api\\ProductRepositoryInterface;
use Magento\\Framework\\View\\Element\\Template;
use Magento\\Framework\\Exception\\NoSuchEntityException;

class Product extends Template
{
    private $productRepository;

    public function \_\_construct(  
        Template\\Context $context,  
        ProductRepositoryInterface $productRepository,  
        array $data \= \[\]  
    ) {  
        $this-\>productRepository \= $productRepository;  
        parent::\_\_construct($context, $data);  
    }

    public function getProductBySku($sku)  
    {  
        try {  
            return $this-\>productRepository-\>get($sku);  
        } catch (NoSuchEntityException $e) {  
            return null;  
        }  
    }  
}

Benefits:

  • Aligns with Magento 2's architectural principles.

  • Improves code testability.

  • Enhances maintainability.

  • Allows for easier implementation swapping.

Method 2: Object Manager Method

While not recommended for production use, this method can be useful for quick testing or prototyping.

Code snippet:

$objectManager \= \\Magento\\Framework\\App\\ObjectManager::getInstance();

$product \= $objectManager-\>get('Magento\\Catalog\\Model\\Product')-\>load($productId);

Considerations:

  • Not recommended for production environments.

  • It can lead to tight coupling and difficulties in testing.

  • Useful for rapid prototyping or administrative scripts.

How To Get Product By SKU in Magento 2?

Step 1: Declare the Command to Get Product SKU

In Magento 2, you can retrieve a product by its SKU using a block class. This class extends \Magento\Framework\View\Element\Template. It uses dependency injection to access the product repository.

1. Create a block class:

namespace Vendor\\Module\\Block;

use Magento\\Framework\\View\\Element\\Template;

use Magento\\Catalog\\Api\\ProductRepositoryInterface;

class Product extends Template  
{  
    protected $productRepository;

    public function \_\_construct(  
        Template\\Context $context,  
        ProductRepositoryInterface $productRepository,  
        array $data \= \[\]  
    ) {  
        $this-\>productRepository \= $productRepository;  
        parent::\_\_construct($context, $data);  
    }

    public function getProductBySku($sku)  
    {  
        try {  
            return $this-\>productRepository-\>get($sku);  
        } catch (\\Magento\\Framework\\Exception\\NoSuchEntityException $e) {  
            return null;  
        }  
    }  
}

This block class injects the ProductRepositoryInterface in the constructor. It provides a method getProductBySku() to retrieve a product by its SKU.

Step 2: Get Product by SKU in Template File

Once you have declared the block class, you can use it in your template file (.phtml) to retrieve and display product information.

1. Create a template file:

\<?php  
/\*\* @var \\Vendor\\Module\\Block\\Product $block \*/  
$sku \= '24-MB01'; // Replace with the desired SKU  
$product \= $block-\>getProductBySku($sku);

if ($product) {  
    echo "Product Name: " . $product-\>getName() . "\<br\>";  
    echo "Product SKU: " . $product-\>getSku() . "\<br\>";  
    echo "Product Price: " . $product-\>getPrice() . "\<br\>";  
    // Add more product information as needed  
} else {  
    echo "Product not found.";  
}

This template file uses the getProductBySku() method from the block class to retrieve the product. It then displays basic product information if the product is found.

Alternative Methods:

1. Using Object Manager (not recommended for production):

$objectManager \= \\Magento\\Framework\\App\\ObjectManager::getInstance();

$product \= $objectManager-\>get('Magento\\Catalog\\Model\\Product')-\>load($productId);

2. Using ProductFactory:

protected $productFactory;

public function \_\_construct(  
    \\Magento\\Catalog\\Model\\ProductFactory $productFactory  
) {  
    $this-\>productFactory \= $productFactory;  
}

public function getProductBySku($sku)  
{  
    return $this-\>productFactory-\>create()-\>loadByAttribute('sku', $sku);  
}

These methods provide options for retrieving product information in Magento 2. The choice depends on specific project requirements and best practices for Magento development.

How to Retrieve a Product by SKU via the Magento 2 API?

How to Retrieve a Product by SKU via the Magento 2 API

The Magento 2 API provides a straightforward method to retrieve product information using a Stock Keeping Unit (SKU). This process involves making an API request to the appropriate endpoint. Here's a detailed explanation of the steps involved:

1. Authentication:

Before accessing the API, you need to authenticate. Magento 2 uses OAuth for API authentication. Obtain an access token by sending a POST request to the token endpoint.

2. API Endpoint:

The endpoint for retrieving a product by SKU is: /V1/products/{sku}

Replace {sku} with the actual SKU of the product you want to retrieve.

3. Making the Request:

Use an HTTP GET request to this endpoint. Include the access token in the Authorization header.

Example using cURL:

$sku \= '24-MB01';  
$apiUrl \= 'https://your-magento-store.com/rest/V1/products/' . $sku;  
$accessToken \= 'your\_access\_token\_here';

$ch \= curl\_init($apiUrl);  
curl\_setopt($ch, CURLOPT\_HTTPHEADER, \[  
    'Authorization: Bearer ' . $accessToken,  
    'Content-Type: application/json'  
\]);  
curl\_setopt($ch, CURLOPT\_RETURNTRANSFER, true);

$response \= curl\_exec($ch);  
curl\_close($ch);

$productData \= json\_decode($response, true);

4. Processing the Response:

The API returns product data in JSON format. Parse this data to extract the required information.

if (isset($productData\['id'\])) {

    echo "Product ID: " . $productData\['id'\] . "\\n";

    echo "Product Name: " . $productData\['name'\] . "\\n";

    echo "SKU: " . $productData\['sku'\] . "\\n";

    echo "Price: " . $productData\['price'\] . "\\n";

} else {

    echo "Product not found or error occurred.";

}

5. Error Handling:

Implement error handling to manage cases where the product is not found or other API errors occur.

if (curl\_errno($ch)) {  
    echo 'Curl error: ' . curl\_error($ch);  
}

if (isset($productData\['message'\])) {  
    echo "API Error: " . $productData\['message'\];  
}

6. Using in Magento 2 Module:

To use this in a Magento 2 module, create a class that extends \Magento\Framework\View\Element\Template and inject the necessary dependencies:

namespace Vendor\\Module\\Block;

use Magento\\Framework\\View\\Element\\Template;  
use Magento\\Catalog\\Api\\ProductRepositoryInterface;

class Product extends Template  
{  
    protected $productRepository;

    public function \_\_construct(  
        Template\\Context $context,  
        ProductRepositoryInterface $productRepository,  
        array $data \= \[\]  
    ) {  
        $this-\>productRepository \= $productRepository;  
        parent::\_\_construct($context, $data);  
    }

    public function getProductBySku($sku)  
    {  
        try {  
            return $this-\>productRepository-\>get($sku);  
        } catch (\\Magento\\Framework\\Exception\\NoSuchEntityException $e) {  
            return null;  
        }  
    }  
}

This method allows for programmatic retrieval of product information by SKU in Magento 2. It utilizes the API for efficient data access. It's particularly useful for integrations with external systems. It's also helpful for creating custom modules that require product data.

Best Practices for Managing SKUs and Getting Products in Magento 2

Category Best Practice Description
SKU Design Consistent Format Use a consistent format for SKUs across all products. It improves readability and helps in programmatic processing.
Meaningful Structure Include relevant product attributes in the SKU (e.g., category, color, size).
Avoid Special Characters Use only alphanumeric characters to prevent issues with database queries or API calls.
Product Retrieval Use Dependency Injection Inject \Magento\Catalog\Api\ProductRepositoryInterface in your class constructor. It follows Magento 2's best practices for dependency management.
Avoid Object Manager Do not use ObjectManager directly in your code. It's not recommended for production environments.
Use Repository Pattern Utilize the ProductRepository class for retrieving products. It's optimized for performance and follows Magento's architectural guidelines.
Code Organization Namespace Usage Properly namespace your classes (e.g., namespace Vendor\Module\Block;) to avoid conflicts and improve code organization.
Extend Appropriate Classes When creating blocks, extend \Magento\Framework\View\Element\Template for proper integration with Magento's layout system.
Performance Implement Caching Cache frequently accessed product data to reduce database load and improve response times.
Optimize Queries When retrieving multiple products, use collection methods instead of loading products individually.
Error Handling Use Try-Catch Blocks Implement try-catch blocks when retrieving products. Use these blocks to handle NoSuchEntityException. Also, handle other potential errors gracefully.
Provide Fallback Options If SKU does not find a product, consider providing fallback options or clear error messages.
API Usage RESTful Endpoints For external integrations, use Magento 2's RESTful API endpoints (/V1/products/{sku}) to retrieve product information.
Proper Authentication Always use proper authentication methods (OAuth) when accessing the API.
Template Files Separation of Concerns In .phtml files, focus on presentation logic. Keep business logic in block classes or models.
Use Block Methods Call methods from your block class to retrieve product information in template files.
Testing Unit Testing Write unit tests for your product retrieval methods to ensure reliability and catch potential issues early.
Integration Testing Perform integration tests. These tests should verify your SKU management. They should also check product retrieval. Ensure everything works correctly within the Magento ecosystem.

FAQs

1. How can I load a product by SKU in Magento 2?

You can load a product by SKU using the product repository class in Magento 2. It involves using the `load product by SKU` method from the Magento\Catalog\Model\ProductRepository class.

2. Can I get the product by ID instead of SKU?

Yes, you can retrieve product information by product ID using the `get product by ID` method from the product repository. It allows you to access product information directly using the product's unique ID.

3. How do I programmatically get product information by product ID?

To get product information by product ID, use the get product by id method. This method is from the Magento\Catalog\Model\ProductRepository. It retrieves the product data based on the provided ID.

4. What namespace do I use when working with product repository in Magento 2?

When working with the product repository, use the PHP namespace Magento\Catalog\Model\ProductRepository. This namespace provides access to methods for loading products. You can use these methods to load products by SKU or ID.

5. What is the significance of using dependency injection in Magento 2?

Using dependency injection in Magento 2 improves code maintainability and testability. It does this by clearly defining class dependencies. It also allows for easier mocking of classes during testing.

6. How can I load product information from a block in a PHTML file?

To load product information from a block in a PHTML file, you can inject the product repository into your block class. Then use these methods: load product by sku or get product by ID. These methods will help you retrieve the desired product information.

CTA

Summary

Magento Get Product By SKU is important for efficient inventory management and order processing. It highlights the unique nature of SKUs. These differentiate products down to the variant level. It enhances precision in inventory tracking and fulfillment. Here's a concise overview:

  • Emphasize SKU Uniqueness: SKUs are important for distinguishing product variants. They are necessary for accurate inventory management and order fulfillment.

  • Programmatic Access: Implement a block class extending \Magento\Framework\View\Element\Template. Use this to fetch product details by SKU. Then, display them effectively in your templates.

  • API Integration: Leverage Magento 2's API for secure and scalable product information retrieval. Ensure proper authentication and response handling.

Explore managed Magento hosting services to enhance performance with get product by SKU.

Andrea Oriane
Andrea Oriane
Technical Writer

Andrea specializes in creating informative content for Magento. With extensive e-commerce knowledge and understanding of Magento functionalities, she crafts articles for a wide range of audience.


Get the fastest Magento Hosting! Get Started