Magento 2: How to Get Customer Data after Login with Observer

Magento 2 How to Get Customer Data after Login with Observer

Hello Magento Friends,

There are certain situations in Magento 2 when you need to do something right after a customer logs in, such as logging login events, redirecting on customer group, or personalizing the user experience. Fortunately, Magento 2 allows you to hook into the customer login process in a clean manner using observers.

Hire Magento Programmer

In this blog, we’ll guide you through how to retrieve customer information after login using an observer in Magento 2.

Steps to Get Customer Data after Login with Observer in Magento 2:

Step 1: First, we need to create an events.xml file inside our extension at the following path

app\code\Vendor\Extension\etc\events.xml

Now add the code as follows

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="customer_login">
        <observer name="log_customer_login" instance="Vendor\Extension\Observer\LogCustomerLogin" />
    </event>
</config>

Step 2: Now, we need to create a LogCustomerLogin.php file inside our extension at the following path

app\code\Vendor\Extension\Observer\LogCustomerLogin.php

Then add the following code

<?php

namespace Vendor\Extension\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer;
use Psr\Log\LoggerInterface;

class LogCustomerLogin implements ObserverInterface
{
    protected $logger;
    public function __construct(LoggerInterface $logger) {
        $this->logger = $logger;
    }
    public function execute(Observer $observer) {
        $customer = $observer->getEvent()->getCustomer();
        $this->logger->info('Customer Login Observer Triggered: ID ' . $customer->getId());
    }
}

Conclusion:

Observers are a great feature in Magento 2 that allow you to react to system events such as customer login. With some easy steps, you can fetch and utilize customer information in real-time to improve the user experience of your store.

Hire Magento Programmer

Relevant Read – Magento 2: How to Get Admin User Data in Observer

Happy Coding!

Previous Article

How to Create Custom Components in React Native?

Next Article

How to Set Up Automatic Daily Database Backup with Laravel 12

Write a Comment

Leave a Comment

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

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨