3

I'm trying to create a piece of code to check if the customer is loggen in or not. I read not to use the objectmanager for that, but I don't know where to put which code.

What I need:

if customer is logged in { Go to my account } else { Login }

How can this be achieved?

I'm using Magento 2.2.6

3
  • where you want to check this? in controller ? Commented Oct 9, 2018 at 10:00
  • I need to do this in: app/design/frontend/theme/themename/Magento_Theme/templates/html/header.phtml Commented Oct 9, 2018 at 10:02
  • Please check my answer and let me know if not solve your question. Commented Oct 9, 2018 at 10:19

2 Answers 2

0

You can use the below code as below:

protected $_custSession; public function __construct( ..... \Magento\Customer\Model\Session $session, ..... ) { ..... $this->_custSession = $session; ..... } //later in your code you can use it as below if ($this->_custSession->isLoggedIn()) { // if customer is logged in } else { // if customer is not logged in } 

Since you are asking your question in phtml you can use the below code:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $customSession = $objectManager->get('Magento\Customer\Model\Session'); if($customSession->isLoggedIn()) { // customer is logged in } else{ //customer is not logged in } 
1
  • 1
    Great! It's working :) I don't know if this is the best and only method to use but it's working at my side. Commented Oct 9, 2018 at 11:10
0

You can make custom helper in and can call in app/design/frontend/theme/themename/Magento_Theme/templates/html/header.phtml

like below:

$helper = $this->helper('Vendor\Module\Helper\Header'); and you can call like:

$helper->isCustomerLoggedIn();

In Vendor\Module\Helper\Header Class you can make one method for check customer is logged in or not

 <?php namespace Vendor\Module\Helper; class Header extends \Magento\Framework\App\Helper\AbstractHelper { public function __construct( \Magento\Framework\App\Helper\Context $context, \Magento\Customer\Model\Session $customerSession ) { $this->_customerSession = $customerSession; parent::__construct($context); } public function isCustomerLoggedIn(){ return $this->_customerSession->isLoggedIn(); } 

}

4
  • Hi Rutvee, I which file should I put which piece of code? Commented Oct 9, 2018 at 11:07
  • make one file Vendor\Module\Helper\Header with above code which answered by me Commented Oct 9, 2018 at 11:08
  • and check in app/design/frontend/theme/themename/Magento_Theme/templates/html/header.phtml using $helper = $this->helper('Vendor\Module\Helper\Header'); $helper->isCustomerLoggedIn(); Commented Oct 9, 2018 at 11:09
  • This same solution is posted all over the place and it simply does not work. No matter what, it returns as not logged in. Commented Jul 17, 2020 at 20:39

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.