DEV Community

Paboda Hettiarachchi
Paboda Hettiarachchi

Posted on

Check if customer is logged in / customer group

  1. This is in reference to Magento 2.4.6 2.\Magento\Customer\Model\Session does not work on product detail page
  2. Say you have a viewModel where you need to check if the customer is logged in or not.
  3. If vendor/magento/module-customer/Model/Layout/DepersonalizePlugin.php is executed before your viewModel it is most likely that the session details are reset.
  4. Best option is to use
protected $httpContext;

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);
}

public function getCustomerIsLoggedIn()
{
    return (bool)$this->httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)