3

how can we get the customer data from id not from customer session in Magento2.

Kindly let me know.

bala.skpm
  • 67
  • 2
  • 2
  • 5

10 Answers10

5

Load the customer by using the api factory. This is the correct way.

<?php

namespace Yourcompany\Customer\Helper {

/**
 * Eav data helper
 */
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    protected $customerRepository;

    public function __construct(
        \Magento\Customer\Api\CustomerRepositoryInterfaceFactory $customerRepositoryFactory) {
        $this->customerRepository = $customerRepositoryFactory->create();
    }

    public function LoadCustomerById($customerId) {
         $cst = $this->customerRepository->getById($customerId);
         return $cst;
    } 

}

?>
Wakar Ahamad
  • 216
  • 1
  • 10
CarComp
  • 1,929
  • 1
  • 21
  • 47
5

You can get all customer data from customer id in Magento 2. Here is the code snippet

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

You can also get customer billing address and shipping address from customer id. Full post is in this link

For the demonstrated purpose I have used Objectmanager. One should always use constructor method.

chirag dodia
  • 515
  • 1
  • 7
  • 17
3

Here is the code snippet to get customer data by using id programmatically in magento 2 version

    use \Magento\Framework\App\Bootstrap; 
    include('app/bootstrap.php'); 
    $bootstrap = Bootstrap::create(BP, $_SERVER);
    $objectManager = $bootstrap->getObjectManager();
    $url = \Magento\Framework\App\ObjectManager::getInstance();
    $storeManager = $url->get('\Magento\Store\Model\StoreManagerInterface');
    $state = $objectManager->get('\Magento\Framework\App\State'); 
    $state->setAreaCode('frontend');
    $websiteId = $storeManager->getWebsite()->getWebsiteId();
    // Get Store ID
    $store = $storeManager->getStore();
    $storeId = $store->getStoreId();
    $customerFactory = $objectManager->get('\Magento\Customer\Model\CustomerFactory'); 
    $customer=$customerFactory->create();
    $customer->setWebsiteId($websiteId);
    //$customer->loadByEmail('example@gmail.com');// load customer by email address
    //echo $customer->getEntityId();
    $customer->load('1');// load customer by using ID
    $data= $customer->getData();
    print_r($data);
Sebastian
  • 4,802
  • 23
  • 48
Vinoth kumar
  • 475
  • 3
  • 14
2

You can get customer data by id by following way

namespace Vendor\Module\Block\Index;

class Index extends \Magento\Framework\View\Element\Template
{

    protected $_customer;

    public function __construct(
        \Magento\Customer\Model\Customer $customer,
        \Magento\Backend\Block\Template\Context $context
    )
    {
        $this->_customer = $customer;
        parent::__construct($context);
    }

     public function getCustomer()
    {
        $customerId = '3'; //You customer ID
        $customer = $this->_customer->getCollection()->addAttributeToFilter('entity_id', array('eq' => '3'));
        print_r($customer->getData());//Customer data by customer ID
    }

}
Prince Patel
  • 2,990
  • 1
  • 21
  • 28
1

It is recommended to use dependency injection instead of using object manager.

Create block like

namespace Lapisbard\General\Block;
use Magento\Customer\Model\Session;

class CustomerAccount extends \Magento\Framework\View\Element\Template {

    public function __construct(
        Session $customerSession,
        \Magento\Framework\View\Element\Template\Context $context
    )
    {
        parent::__construct($context);
        $this->_customerSession = $customerSession;

    }
    public function getCustomerName(){
        $this->_customerSession->getCustomer()->getName();
    }
}

And use it in your template like

<?php echo $block->getCustomerName(); ?>
amitshree
  • 2,048
  • 2
  • 23
  • 41
  • in `__construct()` method you should add also `data` (array) argument. Take a look at some core blocks for example. – Bartosz Kubicki Dec 11 '16 at 11:49
  • If there is no session, you can't get the customer using this method. This makes sense if you are trying to load up a customer's data for use in other ways than during the customer's visit. – CarComp Dec 19 '18 at 14:05
1
 $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $customer = $objectManager->create('Magento\Customer\Model\Customer')->load($customerId);

    $xxx = $customer->getData('xxx'); 
Sam Cheung
  • 31
  • 1
0
 $customer =  $this->objectManager->create('Magento\Customer\Model\Customer')->load(1);

Instead of objectManager you should use dependency injection.

paddz
  • 112
  • 1
  • 8
0

This is the old Ans Magento updated this You can get customer data from following method also more options are available

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

Also you can use Magento\Customer\Model\Customer for blocks using dependency injection.The main benefits of using object manager is it can be used in phtml.

Shine
  • 882
  • 8
  • 15
0

I am facing same problem when Cache enable I am not able to get customer session.But I find below solution

    /**
     * @var \Magento\Customer\Model\Session
     */
    protected $_customerSession;

    public function __construct(Template\Context $context,
            \Magento\Framework\App\Request\Http $request,
            \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
            \Magento\Customer\Model\SessionFactory $customerSession
        ) 
    {
        $this->request = $request;
        $this->customerRepository = $customerRepository;
        $this->_customerSession = $customerSession;
        parent::__construct($context);
    }

    public function getCustomerId(){
        $customer = $this->_customerSession->create();
        var_dump($customer->getCustomer()->getId());
    }

Use above code in block It is working even cache is enable.

Second Solution:

Add cacheable="false" in your xml

<referenceContainer name="content">
     <block class="Vendor\Modulename\Block\Customer" name="customer.session.data" template="Vendor_Modulename::customertab.phtml" cacheable="false" />
 </referenceContainer>

Add below code in block:

    /**
     * @var \Magento\Customer\Model\Session
     */
    protected $_customerSession;

    /**
     * Construct
     *
     * @param \Magento\Framework\View\Element\Template\Context $context
     */
    public function __construct(Template\Context $context,
            \Magento\Framework\App\Request\Http $request,
            \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
            \Magento\Customer\Model\Session $customerSession
        ) 
    {
        $this->request = $request;
        $this->customerRepository = $customerRepository;
        $this->_customerSession = $customerSession;
        parent::__construct($context);
    }

    public function getOrderData(){
        $customerId = $this->_customerSession->getCustomerId();
        var_dump($this->_customerSession->getCustomer());
    }
Prashant Valanda
  • 480
  • 8
  • 19
0

Get Customer Details In Magento2 By Id

use Magento\Customer\Model\CustomerFactory;

class CustomClass {
    /**
     * @var CustomerFactory
     */
    private $customerFactory;
 
    public function __construct(
        CustomerFactory $customerFactory,
    ) {
        $this->customerFactory = $customerFactory;
    }
    
    public function getCustomerDetails() {
    
        $customerId=6;
        // $customerId =$this->getCustomerIdByEmail();
        // $customerId =$this->getCustomerIdByMobile();
   
        $loadData =$this->customerFactory->create()->load($customerId);
        $allData = $loadData->getData());
        
        print_r($allData);
    }
}    

To Get The Customer ID By Email

public function getCustomerIdByEmail() {
  $customerId = $this->customerFactory->create()->getCollection()
                ->addFieldToFilter('email', $email)
                ->getFirstItem()->getId();
}

To Get The Customer ID By Mobile Number

public function getCustomerIdByMobile() {
    $customerId = $this->customerFactory->create()->getCollection()
        ->addFieldToFilter('mobile_number', $mobile_number)
        ->getFirstItem()->getId();
}
Tyler2P
  • 2,324
  • 26
  • 22
  • 31