How To Get Customer Address Data By Address ID In Magento 2
The post gives the solution to get customer address data by address ID in Magento 2.
The Magento 2 store owners may sometimes employ techniques such as restricting the shipping of fragile or heavy items in certain areas to optimize the profit.
Also, managing the shipping process can be easy with organizing the customer addresses, including the ability to add and manage multiple shipping addresses. By allowing customers to save multiple shipping addresses, it becomes easier for them to choose the correct address during the checkout process.
However, to implement such a system needs to get customer address data. The below code is an easy programmatic way to get customer address information using address ID in Magento 2 store.
Customer address data is got by Address ID using AddressRepositoryInterface interface.
Method to Get Customer Address Data by Address ID in Magento 2:
Create GetCustomerAddress.php Class in app/code/Vendor/Extension/Model:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<?php namespace Vendor\Extension\Model; use Magento\Customer\Api\AddressRepositoryInterface; class GetCustomerAddress { private $addressRepository; public function __construct( AddressRepositoryInterface $addressRepository ) { $this->addressRepository = $addressRepository; } public function getAddressDataById($addressId) { try { $addressData = $this->addressRepository->getById($addressId); } catch (\Exception $exception) { throw new \Exception($exception->getMessage()); }; return $addressData; } } |
Now you can access getAddressData($addressId) function as per your requirement by extending GetCustomerAddress class
That’s all for customer address data.
Easy steps, however, doubts in the implementation are welcome in the Comments section below. I’d be glad to help you out.
Please share the solution with the Magento community via social media.
Thank you.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
2 Comments
Where and how can I get the addressId?
Hello Mohmad,
If the customer is registered one then you can get the address ID from order/quote.
It depends on your requirement from where you want to get the data.
Thank You