Get Customer Information From Customer ID in Magento 2
In this code snippet, we will see how to fetch customer information such as email, first name, last name, billing address and shipping address from customer id. You can get logged in customer id from customer session object.
Note: For the demonstrated purpose we have used Objectmanager.Codextblog never recommend the direct use of ObjectManager.One should always use a constructor method to instant an object.
Get Customer Information From Customer ID
<?php $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $customerFactory = $objectManager->get('\Magento\Customer\Model\CustomerFactory')->create(); $customerId = 1; $customer = $customerFactory->load($customerId); //fetch whole customer information echo "<pre>"; print_r($customer->getData()); //fetch specific information echo $customer->getEmail(); echo $customer->getFirstName(); echo $customer->getLastName();
Get Customer Default Billing Address
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $customerFactory = $objectManager->get('\Magento\Customer\Model\CustomerFactory')->create(); $customerId = 1; $customer = $customerFactory->load($customerId); $billingAddressId = $customer->getDefaultBilling(); $address = $objectManager->get('Magento\Customer\Model\AddressFactory')->create()->load($billingAddressId); echo $address->getData('firstname')."<br>"; echo $address->getData('lastname')."<br>"; echo $address->getData('street')."<br>"; echo $address->getData('city')."<br>"; echo $address->getData('region')."<br>"; echo $address->getData('postcode')."<br>"; echo $address->getData('country_id')."<br>";
Get Customer Default Shipping Address
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $customerFactory = $objectManager->get('\Magento\Customer\Model\CustomerFactory')->create(); $customerId = 1; $customer = $customerFactory->load($customerId); $shippingAddressId = $customer->getDefaultShipping(); $address = $objectManager->get('Magento\Customer\Model\AddressFactory')->create()->load($shippingAddressId); echo $address->getData('firstname')."<br>"; echo $address->getData('lastname')."<br>"; echo $address->getData('street')."<br>"; echo $address->getData('city')."<br>"; echo $address->getData('region')."<br>"; echo $address->getData('postcode')."<br>"; echo $address->getData('country_id')."<br>";
Get Customer All Addresses
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $customerFactory = $objectManager->get('\Magento\Customer\Model\CustomerFactory')->create(); $customerId = 1; $customer = $customerFactory->load($customerId); $Addresses = $customer->getAddresses(); foreach ($Addresses as $address){ echo "<pre>"; print_r($address->getData()); }
If you liked this post, then please like us on Facebook and follow us on Twitter.
Leave a Comment
(0 Comments)
Useful Magento 2 Articles
Author Info
Chirag
Connect With Me