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()

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();

}
| improve this answer | |
  • 1
    +1 for the instant reply – Prathap Gunasekaran Mar 8 '19 at 8:32
  • 1
    :D I have already this code so. Btw, Thank You :) – Rohan Hapani Mar 8 '19 at 8:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.