Magento supports Customers with multiple addresses like billing and shipping addresses. Customers can create an address from the My Account Section Address Book tabs from the storefront.
We can get all the list of available customer address by Customer id with AddressRepository Interface. Customer address saved under the customer_address_entity table with parent_id as a customer id.
Useful Interface to fetch all the addresses, Magento\Customer\Api\AddressRepositoryInterface
?php namespace Jesadiya\Address\Block; use Exception; use Psr\Log\LoggerInterface; use Magento\Framework\View\Element\Template; use Magento\Framework\Api\SearchCriteriaBuilder; use Magento\Customer\Api\AddressRepositoryInterface; use Magento\Framework\View\Element\Template\Context; class CustomerAddress extends Template { /** * @var SearchCriteriaBuilder */ protected $searchCriteriaBuilder; /** * @var AddressRepositoryInterface */ protected $addressRepository; /** * @var LoggerInterface */ private $logger; /** * @var array */ private $data; public function __construct( Context $context, LoggerInterface $logger, SearchCriteriaBuilder $searchCriteriaBuilder, AddressRepositoryInterface $addressRepository, array $data = [] ) { $this->logger = $logger; $this->searchCriteriaBuilder = $searchCriteriaBuilder; $this->addressRepository = $addressRepository; parent::__construct($context,$data); } public function getCustomerAddresses($customerId) { $addressesList = []; try { $searchCriteria = $this->searchCriteriaBuilder->addFilter( 'parent_id',$customerId)->create(); $addressRepository = $this->addressRepository->getList($searchCriteria); foreach($addressRepository->getItems() as $address) { $addressesList[] = $address; } } catch (Exception $exception) { $this->logger->error($exception->getMessage()); } return $addressesList; } }
Pass Customer id as $customerId inside the getCustomerAddresses() method.
$customerId = 1; //DYNAMIC_CUSTOMER_ID $customerAddress = $this->getCustomerAddresses($customerId); foreach($customerAddress as $address) { var_dump($address); }
Output:
List of available addresses for the given customer id.