How to Get Base URL in Magento 2

In Magento 1, it was easier to get the base URL using Mage::getBaseUrl(); But, it is not the same case in Magento 2.

You can use the two methods to get base URL in Magento 2:

  1. With Magento Core Method
  2. With Object Manager

I have shown the implementation of both the methods below:

  1. By Magento Core Method
<?php

namespace Mageclues\Custom\Helper;

use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Store\Model\StoreManagerInterface;

class Data extends AbstractHelper
{
    protected $_storeManager;

    public function __construct(
        Context $context,
        StoreManagerInterface $storeManager
    )
    {
        $this->_storeManager = $storeManager;
        parent::__construct($context);
    }

    public function getStoreManagerData()
    {
        $storeUrl = $this->_storeManager->getStore()->getBaseUrl();

        // get Store Url without index.php
        $storeUrl = $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_WEB);

        // get Link Url of store
        $storeLinkUrl = $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_DIRECT_LINK);

        // get media Base Url
        $storeMediaUrl = $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);

        // get Static content Url
        $storeStaticUrl = $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_STATIC);
    }
}

2. By Object Manager

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

$storeManager->getStore()->getBaseUrl();  // to get Base Url
$storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_WEB); // to get Base Url without index.php
$storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_LINK); // to get store link url
$storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA); // to get Base Media url

Let me know in the Comments section below if you have any doubts on the topic. I’d be happy to solve it asap.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *