How to get a customer address by customer ID programmatically

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(
        MagentoStoreModelStoreManagerInterface $storeManager,
        MagentoCustomerModelCustomerFactory $customerFactory,
        MagentoFrameworkAppRequestHttp $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 10nsector 59",
    "city": "1",
    "region": null,
    "country": "KW",
    "postcode": null
}

Note: Using class MagentoCustomerModelCustomerFactory you can get customer-related data that is required as per your requirement.

Searching for an experienced
Magento 2 Company ?
Read More


That’s it.


Source link