Question

I need to programmatically get the country, zip code and state of the store that is at:

Stores->Configuration->SALES->Shipping Settings->Origin enter image description here

Was it helpful?

Solution

Here are the code to get country, region and zip code

<?php

use Magento\Directory\Model\CountryFactory;
use Magento\Directory\Model\RegionFactory;
use Magento\Framework\App\Config\ScopeConfigInterface;

class MyClass
{
    /**
     * @var ScopeConfigInterface
     */
    protected $scopeConfig;

    /**
     * @var CountryFactory
     */
    protected $countryFactory;

    /**
     * @var RegionFactory
     */
    protected $regionFactory;

    /**
     * MyClass constructor.
     * @param ScopeConfigInterface $scopeConfig
     * @param CountryFactory $countryFactory
     * @param RegionFactory $regionFactory
     */
    public function __construct(
        ScopeConfigInterface $scopeConfig,
        CountryFactory $countryFactory,
        RegionFactory $regionFactory
    ) {
        $this->scopeConfig = $scopeConfig;
        $this->countryFactory = $countryFactory;
        $this->regionFactory = $regionFactory;
    }

    /**
     * Get shipping country name
     * @return string
     */
    public function getShippingCountry()
    {
        $countryCode = $this->scopeConfig->getValue(
            'shipping/origin/country_id',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
        $country = $this->countryFactory->create()->loadByCode($countryCode);
        return $country->getName();
    }

    /**
     * Get shipping region name
     * @return string
     */
    public function getShippingRegion()
    {
        $regionId = $this->scopeConfig->getValue(
            'shipping/origin/region_id',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
        $region = $this->regionFactory->create()->load($regionId);
        return $region->getName();
    }

    /**
     * Get shipping postcode
     * @return string
     */
    public function getShippingPostcode()
    {
        return $this->scopeConfig->getValue(
            'shipping/origin/postcode',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top