Magento 2 – How to Get Rewrite Product URL

magento-2.0magento2producturlurl-rewrite

I am trying to get rewrite product url from the load product in custom module. I am getting url in http://localhost/m2/catalog/product/view/id/1401/category/23/ format .

But I want http://localhost/m2/juno-jacket.html

Here is the code

in constructor

public function __construct(
    \Magento\Catalog\Helper\Product $catalogProductHelper,
) {
    $this->catalogProductHelper = $catalogProductHelper;
}

Custom function

public function abc(){
    $product_id = '123';
    return  $this->catalogProductHelper->getProductUrl($product_id);
}

abc() method return url like http://localhost/m2/catalog/product/view/id/1401/category/23/

Best Answer

Here is the method I used to get the product url.

It is definitely not optimal as I have to load the entire product to get it so very bad in terms of performance.

First you need to inject a Magento\Catalog\Model\ProductRepository in your constructor:

use Magento\Catalog\Model\ProductRepository;
//...
public function __construct(
    ProductRepository $productRepository
) {
    $this->_productRepository = $productRepository;
}

Then you load the product based on the product id:

$product = $this->_productRepository->getById($productId);

Finally you can get the URL model to retrieve the rewritten URL:

return $product->getUrlModel()->getUrl($product);