Back to Top

How to get Country Collection in Magento 2

Updated 23 February 2024

To get country collection according to store, you need to add the following code in your file:

<?php
	namespace Webkul\Hello\Block;

	class country extends \Magento\Framework\View\Element\Template {
		
		protected $_countryCollectionFactory;
		public function __construct(
	        \Magento\Directory\Model\ResourceModel\Country\CollectionFactory $countryCollectionFactory,
	        \Magento\Framework\View\Element\Template\Context $context,
	        array $data = []
	    ) {
	        parent::__construct($context, $data);
	        $this->_countryCollectionFactory = $countryCollectionFactory;
	    }

	    public function getCountryCollection()
	    {
	        $collection = $this->_countryCollectionFactory->create()->loadByStore();
	        return $collection;
	    }

	    /**
	     * Retrieve list of top destinations countries
	     *
	     * @return array
	     */
	    protected function getTopDestinations()
	    {
	        $destinations = (string)$this->_scopeConfig->getValue(
	            'general/country/destinations',
	            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
	        );
	        return !empty($destinations) ? explode(',', $destinations) : [];
	    }

	    /**
	     * Retrieve list of countries in array option
	     *
	     * @return array
	     */
	    public function getCountries()
	    {
	        return $options = $this->getCountryCollection()
	                ->setForegroundCountries($this->getTopDestinations())
                        ->toOptionArray();
	    }
}

Here,

getCountries(): is the main function, which you need to call to get collection.

_countryCollectionFactory: is a collection factory of countries.

getCountryCollection(): In this function, we get the country collection by the country factory according to the store.

Searching for an experienced
Magento 2 Company ?
Find out More

getTopDestinations(): in this function, we get different countries’ collections from the system/config, you can change them according to your needs.

I hope this blog will help you with How to get Country Collection in Magento 2. You may also check our wide range of best Magento 2 Extensions.

Please reach out to our team via a support ticket if you have any queries.

Try this and if you have any queries then just comment below 🙂

. . .

Leave a Comment

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


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home