magento2 base url
Magento 2

How to get magento2 base url

How to get magento2 base url.

You want to get magento2 base url for your current store then you can follow this post.

During your daily work, several time, you need to current store base url  and at Magento 1.x version you can get base url using Mage::getBaseUrl();As Magento2, do not used factory patterns, so the code like  Mage::getBaseUrl();  is not exist by which you can base URL.But at Magento2, you should use StoreManager object  and  using  $this->_storeManager->getStore()->getBaseUrl()  you can get base url.

Magento2, use interface, injection of class, that you should  Inject.

Magento\Store\Model\StoreManagerInterface

at Model, Resource model, Block, Helper classes for getting base url using below code:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$baseUrl = $storeManager->getStore()->getBaseUrl();

But this type of object manager calls is a really bad idea.

Best way to get base url ,then first you have to inject Magento\Store\Model\StoreManagerInterface at  __construct() function of your class and then call  getStore()->getBaseUrl()   and get  base URL.

<?php
/**
 * User: Amit Bera
 * Email: [email protected]
 */

namespace {nameSpace};

class {ClassName}
{
    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $storeManager;

    public function __construct(
        \Magento\Store\Model\StoreManagerInterface $storeManager
    )
    {
        $this->storeManager = $storeManager;
    }
    public  function getStoreBaseUrl()
    {
        $storeUrl = $this->storeManager->getStore()->getBaseUrl()
        return $storeUrl;
    }
}

If you want to get base URL with index.php  then use below code:

$baseUrlWithOutIndexPhp = $storeManager->getStore()
->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_WEB);

Best way to get  magento2 base url at Block

If you block class extending   Magento\Framework\View\Element\Template  then you don’t inject StoreManagerInterface at construct function as it already exits at context object

$this->_storeManager = $context->getStoreManager();

So, at your block class you have to call  below code for get the base URL

$this->_storeManager->getStore()->getBaseUrl()