Learn How to Get Logged In Customer Address in Magento 2
Magento geeks ๐๐ผ
Are you looking for a method for how to get the address of a logged in customer in Magento 2? Read this technical solution to find out. ๐๐ผ
There can be several instances where you may require logging details of current users in Magento 2. For instance, recently, one of our clients wanted to get the customer address of a logged in customer for tracking. Here, we are required to get the address of the customer from the current session.
In this blog post, I am going to share the complete method I used – how to get logged in customer addresses in Magento 2 (or get customer address from session.)
Method to Get Logged In Customer Address in Magento 2
In order to get the address of a logged in customer in Magento 2, you can first get the customer id of the logged in customer, which can be later used to retrieve the address.
But this process is long.
We have a straightforward alternate method to do that using AbstractHelper class in the Magento framework.
Hereโs a code snippet to get logged in customer address in Magento 2:
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 28 29 |
<?php namespace Vendor\Extension\Helper; use Magento\Framework\App\Helper\AbstractHelper; use Magento\Framework\App\Helper\Context; class Data extends AbstractHelper { protected $customerAddress; public function __construct( Context $context, \Magento\Customer\Helper\Session\CurrentCustomerAddress $customerAddress ) { $this->customerAddress = $customerAddress; parent::__construct($context); } public function getLoggedInCustomerAddress() { // for Billing Address $billAddress = $this->customerAddress->getDefaultBillingAddress(); // for Shipping Address $shipAddress = $this->customerAddress->getDefaultShippingAddress(); } } |
Use the above code to get a logged in customer address in Magento 2. You can also hide price for not logged in customers in Magento 2, make them login and see the product price.
Thatโs a wrap for this micro-post!
In case of any doubts or queries, please ask in the comments. I would be happy to help.
If this post has added value to your Magento knowledge, hit the five stars & share it with your friends.
Thank You! ๐
Chandresh Chauhan
He has been with Meetanshi for more than three years now as a certified Magento developer. A silent guy whom you can always find solving clients' issues, is an avid reader too.
Prev
How to Test Magento 2 API in Postman? (With Example)
How to Add Facebook Chat to Shopify – Complete Tutorial
Next