Back to Top

How to get a customer address by customer ID programmatically

Updated 30 March 2023

In Magento 2 most of the time we required customer addresses to manage the shipping for tracking etc.
In this blog, We will learn about how to get the customer’s address in API using the customer id or customer token.

The below solution may help you to get the address:

You can use the below code in your API.

    public function __construct(
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Customer\Model\CustomerFactory $customerFactory,
        \Magento\Framework\App\Request\Http $request
    ) {
        $this->storeManager            = $storeManager;
        $this->customerFactory         = $customerFactory;
        $this->_request                = $request;
    }

    public function execute() {
        $customerId = "12";
        $customerFactory = $this->customerFactory->create()->load($customerId);

        if ($customerFactory->getAddresses() != null)
        {
            foreach ($customerFactory->getAddresses() as $address) {
                $allCustomerAddress[] = $address->toArray();
            }
        }

        if ($allCustomerAddress != null)
        {
            foreach ($allCustomerAddress as $customerAddres)
            {
                $returnArray["success"] = true;
                $returnArray["message"] = "";
                $returnArray["street"] = $customerAddres['street'];
                $returnArray["city"] = $customerAddres['city'];
                $returnArray["region"] = $customerAddres['region'];
                $returnArray["country"] = $customerAddres['country_id'];
                $returnArray["postcode"] = $customerAddres['postcode'];
            }
        }
        return $returnArray;
    }

After running this code you will get a response in postman like mentioned below.

{
    "success": true,
    "message": "",
    "street": "h 12 , set 10\nsector 59",
    "city": "1",
    "region": null,
    "country": "KW",
    "postcode": null
}

Note: Using class \Magento\Customer\Model\CustomerFactory you can get customer-related data that is required as per your requirement.

Searching for an experienced
Magento 2 Company ?
Find out More

That’s it.

. . .

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