Magento 2 – How to Get Customer Address by Customer ID

customer-addressmagento-2.1magento2shipping-address

How to get customer address/billing address by customer ID? here's what I've done so far:

$customerId = $_POST["customer_id"];
$customer = $this->_customerRepository->getById($customerId);
$address = $this->_addressRepository->getByCustomerId($customerId);//error

Best Answer

You cannot retrieve an address based on the customer id so this code will never work:

$address = $this->_addressRepository->getByCustomerId($customerId);//error

Because the getByCustomerId method does not exist in the service contract classes.

What you can do though, is use the data service contract customer class with the following code:

$customerId = $_POST["customer_id"];
$customer = $this->_customerRepository->getById($customerId);
$addresses = $customer->getAddresses();

Please note that getAddresses will return an array of Magento\Customer\Api\Data\AddressInterface.

If you need the default billing address you can call:

$billingAddress = $customer->getDefaultBilling();