bala.skpm
bala.skpm

Reputation: 67

Get customer data from id - magento2

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

Kindly let me know.

Upvotes: 3

Views: 46132

Answers (10)

Sanjay Kumar Das
Sanjay Kumar Das

Reputation: 39

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

Upvotes: 0

CarComp
CarComp

Reputation: 2016

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;
    } 

}

?>

Upvotes: 5

chirag dodia
chirag dodia

Reputation: 525

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.

Upvotes: 5

Sam Cheung
Sam Cheung

Reputation: 31

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

    $xxx = $customer->getData('xxx'); 

Upvotes: 1

Prince Patel
Prince Patel

Reputation: 3060

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
    }

}

Upvotes: 2

Vinoth kumar
Vinoth kumar

Reputation: 475

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('[email protected]');// load customer by email address
    //echo $customer->getEntityId();
    $customer->load('1');// load customer by using ID
    $data= $customer->getData();
    print_r($data);

Upvotes: 3

Prashant Valanda
Prashant Valanda

Reputation: 480

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

Upvotes: 0

Shine
Shine

Reputation: 882

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.

Upvotes: 0

amitshree
amitshree

Reputation: 2298

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

Upvotes: 1

paddz
paddz

Reputation: 112

 $customer =  $this->objectManager->create('Magento\Customer\Model\Customer')->load(1);

Instead of objectManager you should use dependency injection.

Upvotes: 0

Related Questions