Get Customer Addresses by Customer ID in Magento 2

 In Magento blog

For converting guest checkout to registered customers 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.

you can get customer addresses by ID in Magento 2 store

<?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
{
    protected $_storeManager;
    protected $_customerFactory;

    public function __construct(
        Context $context,
        StoreManagerInterface $storeManager,
        CustomerFactory $customerFactory
    ) {
        $this->_storeManager = $storeManager;
        $this->_customerFactory = $customerFactory;
        parent::__construct($context);
    }

    public function getCustomerAddressById($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 getCustomerAddressById() to get Address Data
For example : $address = $this->myHelper->getCustomerAddressById(Id);

Leave a Comment

0