Magento2 – Check if Customer is Logged In Not Working

blockscustomermagento2session

I have taken the reference from this link

Created the variable protected $_customerSession;

Done the injection \Magento\Customer\Model\Session $customerSession,

But in my Function in my block class it always returns as false

var_dump($this->_customerSession->isLoggedIn());

Then I tried checking whats Happening in $_SESSION

[_session_validator_data] => Array (
    [remote_addr] => ::1
    [http_via] => 
    )
[_session_hosts] => Array (
    [localhost] => 1
    )
[default] => Array (
    [_form_key] => k9RrgTSkjcgnJ1iZ
    )
[customer_base] => Array (
    [customer_group_id] => 0
    [customer_id] => 
    )
[checkout] =>  Array ( )
[catalog] =>  Array ( )
[reports] => Array (
    [product_index_viewed_count] => 1
    )
[message] =>  Array ( )
[review] =>  Array ( )

My block is extending Template class

use Magento\Framework\View\Element\Template as Template;

My construct function looks like this

public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Vendor\Module\Model\Faq $faq,
        \Vendor\Module\Helper\Data $dataHelper,
        \Magento\Customer\Model\Url $customerUrl,
        \Magento\Framework\Registry $registry,
        \Magento\Customer\Model\Session $customerSession,
        array $data = []
        ) {
            $this->faq = $faq;
            $this->_registry = $registry;
            $this->_dataHelper = $dataHelper;
            $this->_customerUrl = $customerUrl;
            $this->_customerSession = $customerSession;
            parent::__construct($context, $data);
            $this->setTabTitle();
    }

Just to add My php file in my block is custom file in my custom module.

Best Answer

can you try this

public function __construct(
    \Magento\Framework\View\Element\Template\Context $context,
    \Vendor\Module\Model\Faq $faq,
    \Vendor\Module\Helper\Data $dataHelper,
    \Magento\Customer\Model\Url $customerUrl,
    \Magento\Framework\Registry $registry,
    \Magento\Customer\Model\Session $customerSession,
    array $data = []
    ) {
        $this->_isScopePrivate = true;
        $this->faq = $faq;
        $this->_registry = $registry;
        $this->_dataHelper = $dataHelper;
        $this->_customerUrl = $customerUrl;
        $this->_customerSession = $customerSession;
        parent::__construct($context, $data);
        $this->setTabTitle();
}
Related Topic