Magento 2: How to get logged in customer’s id?

Logged In Customer Id Magento 2

We will check How to get logged in customer’s id? in this post.

We need to read the customer sessions in order to get the current logged-in customer-id. This post shows you by reading customer sessions from your own service class. We also checked whether a customer is logged in or not.

Let’s see how we can get logged in customer-id in Magento 2

How to get logged in customer’s id?

Create Service Class

SbDevBlog\Cusomer\Services\CurrentCustomer
<?php
namespace SbDevBlog\Customer\Services;

use Magento\Customer\Model\Session;


class CurrentCustomer
{
    /**
     * @var Session
     */
    protected Session $customerSession;

    /**
     * Constructor
     *
     * @param Session $customerSession
     */
    public function __construct(
        Session $customerSession,
    ) {
        $this->customerSession = $customerSession;
    }

    /**
     * Get Current Customer Id
     *
     * @return int
     */
    public function getCurrentCustomerId() {
        $this->customerSession->getCustomerId(),
    }

    /**
     * Check Whether Customer is logged in
     *
     * @return boolean
     */
    public function isLoggedInCustomer()
    {
      return $this->customerSession->isLoggedIn()
    }
}

This is the easiest way to get current customer details on the front end. However, You may face the issue that you may get a null value for the current customer if you use a cache like FPC (Full Page Cache) or varnish, or any. Thanks for reading the post How to get logged in customer’s id?

You need to bind customer data with httpcontext in such scenario. Check the post given in link for the solution. https://sbdevblog.com/magento-2-how-to-get-current-customer-id-while-fpc-is-enabled/

Download Source Code

Note: Please verify the code of this blog and the relevant git repository before using it in production.
sb dev blog adobe commece Magento 2

🙂 HAPPY CODING 🙂

One thought on “Magento 2: How to get logged in customer’s id?

Leave a Reply

Your email address will not be published. Required fields are marked *