Get Region id by region and Country code in Magento 2.

You Can fetch Region id by region code and the country code in Magento 2.

There are many scenarios where you need to get region id to do the process. like Create Customer address programmatically, You need to required Region Id to store region for customer address.

You can get region id by calling the factory method of Region Class.

You need to call Magento\Directory\Model\Region class in __construct() function as dependency.

<?php
namespace Rbj\Customer\Model;

use Magento\Directory\Model\RegionFactory;

/**
 * Class CreateCustomerAddress
 */
class CreateCustomerAddress
{
    /**
     * @param RegionFactory $regionFactory
     */
    private $regionFactory;

    /**
     * @param RegionFactory $regionFactory
     */
    public function __construct(
        RegionFactory $regionFactory
    ) {
        $this->regionFactory = $regionFactory;
    }


    /**
     * @param $stateCode
     * @param $countryId
     * @return int
     */
    public function getRegionId($stateCode, $countryId): int
    {
        $regionId = (int)$this->regionFactory->loadByCode($stateCode, $countryId)->getRegionId();
        return $regionId;
    }

You can call function with below way,

echo $this->getRegionId(‘CA’, ‘US’);

California Region id is 12.
Output: 12