How to get Default billing and Shipping address of current customer in magento 2?

In Magento 2 we can get the Current Customer Default billing and Shipping address using the given code snippet.

If the Customer is not logged in they will display customer is not logged in.
Using Block file get logged in customer default billing and shipping address,

<?php
namespace Rbj\CustomerAddress\Block;

class Addressinfo extends \Magento\Framework\View\Element\Template
{
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Customer\Helper\Session\CurrentCustomerAddress $currentCustomerAddress,
        \Magento\Customer\Model\Address\Config $addressConfig,
        \Magento\Customer\Model\Address\Mapper $addressMapper,
        \Magento\Framework\App\Http\Context $httpContext,
        array $data = []
    ) {
        $this->currentCustomerAddress = $currentCustomerAddress;
        $this->_addressConfig = $addressConfig;
        $this->addressMapper = $addressMapper;        
        $this->httpContext = $httpContext;
        parent::__construct($context, $data);
    }

    /**
     * Array for Shipping Address
     *
     * @return \Magento\Framework\Phrase|string
     */
    public function getDefaultShippingAddress()
    {
        try {
            $address = $this->currentCustomerAddress->getDefaultShippingAddress();
        } catch (NoSuchEntityException $e) {
            return __('You have not set a default shipping address.');
        }
        return $address;
    }

    /**
     * Array for Billing Address
     *
     * @return \Magento\Framework\Phrase|string
     */
    public function getDefaultBillingAddress()
    {
        try {
            $address = $this->currentCustomerAddress->getDefaultBillingAddress();
        } catch (NoSuchEntityException $e) {
            return __('You have not set a default billing address.');
        }
        return $address;
    }
    /* Html Format */
    public function getDefaultShippingAddressHtml($address) {
        if ($address) {
            return $this->_getAddressHtml($address);
        } else {
            return __('You have not set a default Shipping address.');
        }
    }
    /* Html Format */
    public function getDefaultBillingAddressHtml($address) {
        if ($address) {
            return $this->_getAddressHtml($address);
        } else {
            return __('You have not set a default billing address.');
        }
    }

    /**
     * Render an address as HTML and return the result
     *
     * @param AddressInterface $address
     * @return string
     */
    public function _getAddressHtml($address)
    {
        /** @var \Magento\Customer\Block\Address\Renderer\RendererInterface $renderer */
        $renderer = $this->_addressConfig->getFormatByCode('html')->getRenderer();
        return $renderer->renderArray($this->addressMapper->toFlatArray($address));
    }

    /*
     * return bool
     */
    public function getLogin() {
        return $this->httpContext->isLoggedIn();
    }
}

Call a required function in the template file,

<?php
$isLoggedin = $block->getLogin(); //output for logged in customer as 'roni_cost@example.com'
if($isLoggedin) {
    $shippingAddress = $block->getDefaultShippingAddress();
    //echo "<pre>";print_r($shippingAddress->__toArray());
    $billingAddress = $block->getDefaultBillingAddress();
    //echo "<pre>";print_r($billingAddress->__toArray());
    echo $block->getDefaultShippingAddressHtml($shippingAddress);
    echo $block->getDefaultBillingAddressHtml($billingAddress);
} else {
    echo __('You have not logged in.');
}

Output for the customer has a shipping address exist,

echo "<pre>";print_r($shippingAddress->__toArray());

Array
(
    [firstname] => Rakesh
    [lastname] => Jesadiya
    [street] => Array
        (
            [0] => 61460 Honey Street Parkway
        )

    [city] => Hollywood
    [country_id] => US
    [region] => Array
        (
            [region] => Michigan
            [region_code] => MI
            [region_id] => 33
        )

    [region_id] => 33
    [postcode] => 49628-7978
    [telephone] => (555) 229-3326
    [id] => 1
    [customer_id] => 1
    [default_billing] => 1
    [default_shipping] => 1
)

Output for HTML format of the Shipping address,

Rakesh Jesadiya
61460 Honey Street Parkway
Hollywood, Michigan, 49628-7978
United States
T: (555) 229-3326

How to check if customer is logged in or not in magento 2?

In Magento 2 we can check Customer is logged in or not by checking the given article,
Using the Block file, Pass Magento\Framework\App\Http\Context as a dependency to construct the method.

<?php

namespace Rbj\Customer\Block;

class Customerinfo extends \Magento\Framework\View\Element\Template
{
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Framework\App\Http\Context $httpContext,
        array $data = []
    ) {
        $this->httpContext = $httpContext;
        parent::__construct($context, $data);
    }

    /*
     * return bool
     */
    public function getLogin() {
        return $this->httpContext->isLoggedIn();
    }
?>

Call getLogin function in the template file,

$isLoggedin = $block->getLogin();
if($isLoggedin) {
    // show your message
}

Never use Object Manager directly in real code in Magento 2.

Here I have shown just a demonstration using Objectmanager. Using Objectmanager directly create performance issue for the site.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$userContext = $objectManager->get('Magento\Framework\App\Http\Context');
$isLoggedIn = $userContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
if($isLoggedIn) {
// do coding for customer loggin
}

How to get customer data by customer email in magento 2?

You can get customer information by just passing the customer email using below code snippet, Create Block file,

To Fetch Customer Data in Magento by customer email ID, you required a customer email id and an optional website id to fetch the correct data.

<?php
declare(strict_types=1);

namespace Rbj\Customer\Model;

use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;

class CustomerDetail
{
    public function __construct(CustomerRepositoryInterface $customerRepository )
    {
        $this->customerRepository = $customerRepository;
    }

    /**
     * @param string $email
     * @param ?int $websiteId
     * @return CustomerInterface
     * @throws LocalizedException
     */
    public function getCustomerByEmail(string $email, int $websiteId = null): CustomerInterface
    {
        try {
            $customer = $this->customerRepository->get($email, $websiteId);
        } catch (NoSuchEntityException $exception) {
            throw new LocalizedException(__('Provided Customer no longer exists.'));
        }
        
        return $customer;
    }
}

Continue reading “How to get customer data by customer email in magento 2?”