In Magento 2, you can use the \Magento\Directory\Model\Country model and the \Magento\Store\Model\StoreManager class to get the list of allowed countries by store code. Here is an example of how you can do this:
- Inject the \Magento\Directory\Model\Country model and the \Magento\Store\Model\StoreManager class into your class constructor.
use Magento\Directory\Model\Country;
use Magento\Store\Model\StoreManager;
class YourClass {
protected $country;
protected $storeManager;
public function __construct
(
Country $country, StoreManager $storeManager
) {
$this->country = $country;
$this->storeManager = $storeManager;
}
}
- Get the store code by using the getCode() method of the StoreManager class.
$storeCode = $this->storeManager->getStore()->getCode();
- Use the getAllowedCountries method of the Country model and pass the store code as a parameter.
$allowedCountries = $this->country->getAllowedCountries($storeCode);
This will return an array of allowed countries for the store with the specified store code.
Please note that the allowed countries can be defined in the store configuration settings.
You can also filter the countries by using the getList method of the Country model and passing the allowed countries array as a parameter.
> $countries = $this->country->getList(); $allowedCountries =
> array_intersect_key($countries, array_flip($allowedCountries));