2

I am trying to get First Name and Last Name from the session. But I am not able to get First name or last name.

Instead, I am able to get the full name.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
$customerSession = $objectManager->create('Magento\Customer\Model\Session');


$customer_name = $customerSession->getCustomer()->getName();  // gives me result

But when I try to get first it returns null

$customer_first_name = $customerSession->getCustomer()->getFirstName();  // gives me null

How to get the first name using customerSession->getCustomer()

summu
  • 847
  • 18
  • 48

1 Answers1

2

You should inject \Magento\Customer\Api\CustomerRepositoryInterface in your construct :

protected $customerRepository;
public function __construct(
\Magento\Customer\Api\CustomerRepositoryInterface $customerRepository 
){
  $this->customerRepository = $customerRepository;
}
public function getCustomerData()
{
  $customer = $this->customerRepository->getById($customerId);
  if($customer->getId()){
      echo $customer->getFirstname();
      echo $customer->getLastname();
  }
}

Using Object Manager :

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerRepository = $objectManager->create(\Magento\Customer\Api\CustomerRepositoryInterface::class);
$customer = $customerRepository->getById('your customer id');
if($customer->getId()){
    echo $customer->getFirstname();
    echo $customer->getLastname();

}
Rohan Hapani
  • 17,388
  • 9
  • 54
  • 96