How to get Base url, Media url, Static url and Link url in Magento 2?

Whenever you are working with Magento 2 many times you require to get Base URL, Media URL, and Static URL. Today, in this article I will show you how to get the Base URL, Media URL and Static URL using the dependency injection method.

<?php
namespace Vendor\Module\Block;

class MyBlock extends \Magento\Framework\View\Element\Template
{    
    public $_storeManager;

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        array $data = []
    )
    {    
        $this->_storeManager = $storeManager;
        parent::__construct($context, $data);
    }

    public function getBaseUrl(){
       return $this->_storeManager->getStore()->getBaseUrl();
    }
    
    public function getMediaUrl(){
       return $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
    }
    
    public function getStaticUrl(){
       return $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_STATIC);
    }

    public function getLinkUrl(){
       return $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_LINK);
    }
}

Leave a Reply

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