In this post I am going to explain how to get country collection in Magento 2.
1. Using Dependency Injection
Add below code snippet in Block class.
protected $_countryCollectionFactory;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Directory\Model\ResourceModel\Country\CollectionFactory $countryCollectionFactory,
array $data = []
)
{
$this->_countryCollectionFactory = $countryCollectionFactory;
parent::__construct($context, $data);
}
public function getCountryCollection()
{
$collection = $this->_countryCollectionFactory->create()->loadByStore();
return $collection;
}Add below code snippet in template file.
// Get country collection $countryCollection = $block->getCountryCollection(); echo "<pre>"; print_r($countryCollection->getData()); echo "</pre>";
2. Using Object Manager
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$countryCollectionFactory = $objectManager->get('Magento\Directory\Model\ResourceModel\Country\CollectionFactory');
// Get country collection
$countryCollection = $countryCollectionFactory->create()->loadByStore();
echo "<pre>";
print_r($countryCollection->getData());
echo "</pre>";
Write an article about ecommerce that help people to grow their ecommerce business. You’ll find best ecommerce guide, news, tips & more!


Leave a Reply