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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay