Magento 2 get base url


Magento 2 get base url – In magento 1.x we use Mage::getBaseUrl(); but in magento 2.0 it is different to get the base url than the magento 1.x. Here in this tutorial we are going to explain how you can get the base url, media url and link url on phtml, blocks, controllers & models in magento 2.0, media url etc.


Magento 2 get base url

You can get base url in magento 2.0 as below –

Magento 2 get base url – Method 1

Magento2 get base url : Example

$baseUrl = $this->_storeManager->getStore()->getBaseUrl();
echo $baseUrl; //will give base url

The above example will give you base url in magento2.

Magento 2 get base url – Method 2

Using this method you can get base url anywhere on – phtml, blocks, controllers or models also get base url using the following method –

Magento2 get base url : Example

$storeId = 1; // add your store id
$baseUrl = $this->_objectManager->get('Magento\Store\Model\StoreManagerInterface')
                     ->getStore($storeId)
                     ->getBaseUrl();
echo $baseUrl;

The above example will give you base url in magento2.

Magento 2 get media url – Method 2

You can get media base url using the following method –

Magento2 get media url : get Media Path Example

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

The above example will give you media base url in magento2.

Magento 2 get link url – Method 2

You can also get link base url using the following method –

Magento2 get link url : get link Path Example

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

The above example will give you link base url in magento2.


Advertisements

Add Comment

📖 Read More