Magento – How to get customer billing and shipping information in magento2 .phtml files

billing-addresscustomermagento2shipping-address

How to get checkout page information (firstname, lastname, address etc of customer) ,
I have created one phtml file and the code is below

$address = $objectManager->get('\Magento\Sales\Model\Order');

        echo   $address->getBillingAddress()."<br/>";  
        echo   $address->getShippingAddress()."<br/>";  

I need to get customer information irrespective of his/her login.
how can I achieve it, thanks.

Best Answer

Factory Method :

You need to inject \Magento\Customer\Model\CustomerFactory and \Magento\Customer\Model\AddressFactory in your construct

protected $_customerFactory;
protected $_addressFactory;

public function __construct(
    .............
    \Magento\Customer\Model\CustomerFactory $customerFactory,
    \Magento\Customer\Model\AddressFactory $addressFactory
    .............
)
{
    .............
    $this->_customerFactory = $customerFactory;
    $this->_addressFactory = $addressFactory;
    .............
}

then add this below code in your function

//get customer model before you can get its address data
$customer = $customerFactory->create()->load(1);    //insert customer id

//billing
$billingAddressId = $customer->getDefaultBilling();
$billingAddress = $this->_addressFactory->create()->load($billingAddressId);


//shipping
$shippingAddressId = $customer->getDefaultShipping();
$shippingAddress = $this->_addressFactory->create()->load($shippingAddressId);

Object Manager Method :

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerID = 1;
$customer = $objectManager->create('Magento\Customer\Model\CustomerFactory')->load($customerID);
$addressFactory = $objectManager->create('Magento\Customer\Model\AddressFactory');

$billingAddressId = $customer->getDefaultBilling();
$billingAddress = $addressFactory->load($billingAddressId);

$shippingAddressId = $customer->getDefaultShipping();
$shippingAddress = $addressFactory->load($shippingAddressId);

Using Order ID :

$orderID = 100;

$orderObj = $objectManager->create('Magento\Sales\Model\Order')->load($orderID);

$shippingAddressObj = $orderObj->getShippingAddress();

$shippingAddressArray = $shippingAddressObj->getData();

$BillingAddressObj = $orderObj->getBillingAddress();

$BillingAddressArray = $BillingAddressObj->getData();

Get order ID :

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$checkout_session = $objectManager->get('Magento\Checkout\Model\Session');
$order = $checkout_session->getLastRealOrder();
$orderID = $order->getIncrementId();

For better coding standard, Don't use Object Manager Directly.

Related Topic