Magento 2 get media path

Today we discuss about Magento 2 get media path .This tutorial include how to get media path in your block or phtml file. There are two ways to do it. One is factory method and other is use object manager. So let start with our example.

Factory Method

In this example we will get media path. First your need to inject \Magento\Store\Model\StoreManagerInterface.

<?php
/**
* Simple Hello World Module
*
* @category QaisarSatti
* @package QaisarSatti_HelloWorld
* @author Muhammad Qaisar Satti
* @Email qaisarssatti@gmail.com
*
*/

namespace QaisarSatti\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{
protected $storeManager;

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

public function getMediaUrl()
{
    return $mediaUrl = $this->storeManager
                     ->getStore()
                     ->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
   
}


}

Object Manager

In this example we will get media path. Using object manager is not recommended.

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

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!

Leave a Reply