How to get product name in Magento 2?

Member

by domenico , in category: PHP CMS , 8 months ago

How to get product name in Magento 2?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by aniya.jaskolski , 3 months ago

@domenico 

In Magento 2, you can get the product name by using the following code:

1
2
3
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$product = $objectManager->get('MagentoCatalogModelProduct')->load($productId);
$productName = $product->getName();


Here, $productId is the ID of the product for which you want to get the name.


Keep in mind that the above code uses the object manager, which is considered an anti-pattern in Magento 2. It is recommended to use dependency injection instead of the object manager to create an instance of a class.


For example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
use MagentoCatalogApiProductRepositoryInterface;

...

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

...

$product = $this->productRepository->getById($productId);
$productName = $product->getName();