0

This question already has an answer here:

I have used the following code to check the user is logged or not. It always show me "Login Failed" after the user is logged to the site also.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
 if($customerSession->isLoggedIn()) 
   {  
    echo'login success';
   }

  else {

   echo 'login failed';
  }

marked as duplicate by Raphael at Digital Pianism, Rakesh Jesadiya, Khoa TruongDinh, Rajeev K Tomy, Amit Bera Nov 3 '16 at 6:46

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

0

Instead of this

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
 if($customerSession->isLoggedIn()) 

Use this. Its working fine for me

$ObjectManager= \Magento\Framework\App\ObjectManager::getInstance();
$context = $ObjectManager->get('Magento\Framework\App\Http\Context');
$isLoggedIn = $context->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
if($isLoggedIn)
0

Taking example from \Magento\Checkout\Model\Session, I would use the recommended approach via DI instead the suggested versions with ObjectManager:

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

In your constructor:

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

and then in your code:

if(this->_customerSession->isLoggedIn()){  
  // ... your logic here
}

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