Magento – How to get customer’s addresses using CustomerId

customer-addressmagento2

I am trying to get all the addresses of a customer using below code. But here I am not able to fetch all the details. If I try to print the array $customerAddres it give me memory exhausted error in terminal.

$customer = $this->_customers->load(3);
    $addresses = $customer->getAddresses();
    foreach ($addresses as $address) {
        $customerAddress[] = $address->toArray();
    }
    foreach ($customerAddress as $customerAddres) {
        echo $customerAddres['street'];
    }

If anyone can help me to get complete addresses of a customer please let me know.

Best Answer

Try following way:


protected $customerRepository;

public function __construct(
    \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository
) {
    $this->customerRepository = $customerRepository;
}

And now


$customer = $this->customerRepository->getById(2);
/** @var \Magento\Customer\Api\Data\AddressInterface $address */
foreach ($customer->getAddresses() as $address) {
    print_r($address->getStreet());
}
Related Topic