Magento2 Base URL – How to Retrieve

base-urlmagento2url

In Magento 1 Mage::getBaseUrl();, but in Magento 2 I have to pass responsible class object type in constructor.

I don’t have the idea which class I have to pass?

Best Answer

In magento 2.

If you want to get Base url ,then you can try below code:

/**
* @var \Magento\Store\Model\StoreManagerInterface $this->_storeManager
*/

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

Where $this->_storeManager instance of \Magento\Store\Model\StoreManagerInterface

this above code will give you result

http://www.example.com (If Seo rewrite is enable)

And http://www.example.com/index.php (If Seo rewrite is not enable)

If you want Base URL without index.php

$this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_WEB)

See in details at magento2 get base url and media url and static url

Using Object Manager

Base Url:

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

Base Url without index.php

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

For getting media base url:

$this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);

for getting link url:

$this->_storeManager->getStore()
           ->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_LINK);

Edit

For getting the $this->_storeManager You should call inject \Magento\Store\Model\StoreManagerInterface $storeManager

at __construct( ) function at block class

just like :

public $_storeManager;
  public function __construct(
      \Magento\Store\Model\StoreManagerInterface $storeManager,
       .....
    ) {
       ...
  $this->_storeManager=$storeManager;
    }

Updated:

Also,you can get base url directly at phtml using direct call of object Manager.

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

Note: Directly call of object manager is not good idea. If you want base url at phtml then inject StoreManagerInterface at block