If you want to implement any features in the Magento 2 store based on the customer address, this post is for you.
For example, while implementing guest checkout and then automatically converting them to registered customers, get the customer ID, without relying on session data as it is very necessary. For that, you’d need the customer address. But what if the already signed up customer uses guest checkout! The duplicate addresses are saved and it will mess up the address database.
To avoid that, you can get customer addresses by customer ID in Magento 2 store and then check for duplicate values.
The below solution helps you collect all customer addresses using customer ID:
Method to Get Customer Addresses by Customer ID in Magento 2:
<?php namespace [Vendor]\[Module]\Helper; use Magento\Framework\App\Helper\AbstractHelper; use Magento\Framework\App\Helper\Context; use Magento\Store\Model\StoreManagerInterface; use Magento\Customer\Model\CustomerFactory; class Data extends AbstractHelper { private $storeManager; private $customerFactory; public function __construct( Context $context, StoreManagerInterface $storeManager, CustomerFactory $customerFactory ) { $this->storeManager = $storeManager; $this->customerFactory = $customerFactory; parent::__construct($context); } public function getCustomerAddress($customerId) { $customer = $this->customerFactory->create(); $websiteId = $this->storeManager->getStore()->getWebsiteId(); $customer->setWebsiteId($websiteId); $customerModel = $customer->load($customerId); $customerAddressData = []; $customerAddress = []; if ($customerModel->getAddresses() != null) { foreach ($customerModel->getAddresses() as $address) { $customerAddress[] = $address->toArray(); } } if ($customerAddress != null) { foreach ($customerAddress as $customerAddres) { $street = $customerAddres['street']; $city = $customerAddres['city']; $region = $customerAddres['region']; $country = $customerAddres['country_id']; $postcode = $customerAddres['postcode']; $customerAddressData[] = $customerAddres->toArray(); } } return $customerAddressData; } }
Note: Using [Vendor]\[Module]\Helper class’s object you can call method getCustomerAddress(id) to get Address Data
For example : $address = $this->myHelper->getCustomerAddress(5);
That’s it.
Do share the solution with fellow developers via social media.
Thanks.