Magento2 How to Get Country Code Collection

Magento2 How to Get Country Code Collection
To get country list data, you need to create instance of Country collection model `Magento\Directory\Model\ResourceModel\Country\CollectionFactory`. Once instance is created, you can load it by current store.
<?php 
namespace Knowthemage\Hello\Block;

use Magento\Framework\View\Element\Template\Context;
use Magento\Directory\Model\ResourceModel\Country\CollectionFactory;

class Country extends \Magento\Framework\View\Element\Template {

	/**
	 * @var CollectionFactory
	 */
	protected $_countryCollectionFactory;

	/**
	 * Country constructor.
	 * @param CollectionFactory $countryCollectionFactory
	 * @param Context $context
	 * @param array $data
	 */
	public function __construct(
		CollectionFactory $countryCollectionFactory,
		Context $context,
		array $data = []
	) {
		parent::__construct($context, $data);
		$this->_countryCollectionFactory = $countryCollectionFactory;
	}

	/**
	 * Get Country collection
	 *
	 * @return mixed
	 */
	public function getCountryCollection()
	{
		return $this->_countryCollectionFactory->create()->loadByStore();
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *