Magento, Magento 2

How to Get Store Config Value in Magento 2

How to Get Store Config Value in Magento 2

In this tutorial, Today I will explain to you how to get the store config value in Magento 2. Magento 2 allows you to set configuration value by different scopes like specific website, specific store and specific store view. So, It’s required to get store configuration value by scope in Magento 2. Generally, When user wants to access the value in whole website at that time, store configuration needs to create and set value in that to access value everywhere.

In Magento 2, There is all configuration value set in the core_config_data table. So, Let’s follow the below steps.

You may also like this :

Let’s assume that you have created a module. Now, you need to create a helper file in your module at app/code/RH/Helloworld/Helper/Data.php

Solution 1 :

<?php
/**
 * Created By : Rohan Hapani
 */
namespace RH\Helloworld\Helper;

use Magento\Store\Model\ScopeInterface;
use Magento\Framework\App\Helper\AbstractHelper;

class Data extends AbstractHelper
{
    const XML_CONFIG_PATH = 'config/to/path';

    public function getConfig()
    {
        $configValue = $this->scopeConfig->getValue(self::XML_CONFIG_PATH,ScopeInterface::SCOPE_STORE); // For Store
        /**
         * For Website
         * 
         * $configValue = $this->scopeConfig->getValue(self::XML_CONFIG_PATH,ScopeInterface::SCOPE_WEBSITE);
         */
         return $configValue;
    }
}

Solution 2 :

<?php
/**
 * Created By : Rohan Hapani
 */
namespace RH\Helloworld\Helper;

use Magento\Framework\App\Helper\AbstractHelper;

class Data extends AbstractHelper
{
    const XML_CONFIG_PATH = 'config/to/path';

    /**
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    protected $scopeConfig;

    /**
     * @param  \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     */
    public function __construct(
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
    ) {
        $this->scopeConfig = $scopeConfig;
    }

    public function getConfig($path, $storeId = null)
    {
        return $this->scopeConfig->getValue(
            $path,
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
            $storeId
        );
    }

    public function isEnabled()
    {
        return $this->getConfig(self::XML_CONFIG_PATH, 1); // Pass store id in second parameter
    }
}

Now, you can inject the helper class anywhere and use the getConfig() function to get config value.

I hope this blog will helpful for easily understand how to get the store config value in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution.

Keep liking and sharing 🙂
Tagged ,