Quantcast
Channel: Webkul Blog
Viewing all articles
Browse latest Browse all 5490

Get Customer ID Without Session in Magento 2

$
0
0

We will Get Customer ID Without Session in Magento 2.

You can get the customer Id using through the customer session but if you want to get customer id without using customer session you can you the follow code.

You can get customer ID without using session in Magento 2 and hence avoid issues like

> A NULL value is returned even if the customer is logged in.
> You have to disable the cache, and hence low page speed.
> It does not return customer ID.

So That I given another solution which does not generate any issues and doesn’t require disabling cache.

<?php

namespace Webkul\Customer\Helper;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
   /**
     * @var \Magento\Framework\App\Helper\Context
   */

   protected $userContext;

   public function __construct(
    \Magento\Framework\App\Helper\Context $context,
    \Magento\Authorization\Model\UserContextInterface $userContext
  )
  {
    $this->userContext = $userContext;
    parent::__construct($context);
  }

  public function getCustomerId()
  {
    return $this->userContext->getUserId();
  }
}

I hope your issue hence been resolve.

If any issue or doubt please feel free to mentioned in comment section.

I would be happy to help.

Happy Coding!!! 🙂


Viewing all articles
Browse latest Browse all 5490

Trending Articles