Question

I want to check if a customer is logged or not. And if he/she logged, I want to get the customerId. I just googled but I could find 2 ways. One is to use CustomerSession: Magento\Customer\Model\Session Another one is to use Customer\Model\Context. Magento\Customer\Model\Context::CONTEXT_AUTH

Which is right way? These 2 articles show different way. I am really confusing what I should use. http://www.blogtreat.com/get-logged-in-customer-data-in-magento-2/

Magento 2: get customer id of logged in user with cache enabled

Thanks.

Was it helpful?

Solution

you can try Following Way..

In Magento 2 we can check Customer is logged in or not by below way, Using Block file, Pass Magento\Framework\App\Http\Context as a dependency to construct method.

    <?php
    namespace Rakesh\Customer\Block;

    class Customerinfo extends \Magento\Framework\View\Element\Template
    {
        public function __construct(
            \Magento\Framework\View\Element\Template\Context $context,
            \Magento\Framework\App\Http\Context $httpContext,
            array $data = []
        ) {
            $this->httpContext = $httpContext;
            parent::__construct($context, $data);
        }
        /*
         * return bool
         */
        public function getLogin() {
            return $this->httpContext->isLoggedIn();
        }
    ?>

Call getLogin function in template file,

$isLoggedin = $block->getLogin();
if($isLoggedin) {
    // show your message
}

OTHER TIPS

You shouldn't use dependency injection into your .phtml files. I'll leave you an example of how to check it in a Helper class.

use Magento\Framework\App\Helper\AbstractHelper;

class Data extends AbstractHelper
{
    /**
     * @var \Magento\Framework\App\Http\Context
     */
    private $httpContext;    

public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Framework\App\Http\Context $httpContext
    ) {
        parent::__construct($context);
        $this->httpContext = $httpContext;
    }

public function isLoggedIn(){
            $isLoggedIn = $this->httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
            return $isLoggedIn;
    }
}

Then you can call this in your phtml in order to obtain the value:

$myhelper = $this->helper('Vendor\Module\Helper\Data'); 
$isloggedin = $myhelper->isLoggedIn();
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top