cancel
Showing results for 
Search instead for 
Did you mean: 

Getting Customer Session

Getting Customer Session

 Hi Guys,

 

I've a helper and in the __construct() something like:

 

 

    public function __construct(
        Context $context,
        \Magento\Customer\Model\Session $customerSession
    )
    {
        parent::__construct($context);

        $this->_customerSession = $customerSession;
        
    }

The problem is when I can the $_customerSession object data it's empty, even though I've logged in.

 

 It seems the session is instantiated at a later point in the process, because if I call the customer\Session object in a page Model or block it works fine. In fact, the whole store works as expected. I can see the logged in welcome message in the top right bar, add products to cart, login.

 

The code above is dispatched in the event 

catalog_product_get_final_price


How do I make sure the session is loaded or how do I know when it's loaded?

 

Regards

3 REPLIES 3

Re: Getting Customer Session

 

You can use 

 

\Magento\Framework\App\Http\Context $httpContext

 

$this->_httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH)

 

to check if a customer is logged in

Re: Getting Customer Session

Hi,

 

Thanks for your message, but it only gives you the logged  status, and not the customer ID.

 

Regards 

Re: Getting Customer Session

add following variable into your class

 

  

protected $_customerSession;

 

on your class constructor

 

  

public function __construct(
    \Magento\Customer\Model\Session $customerSession,
) {
    $this->_customerSession = $customerSession;
}

 

use following code in your function

  

$customerId = $this->customerSession->getCustomerId();