Magento 2 – How to Add Custom Data to Customer Session

customer-sessionmagento2

In LoginPost controller using this "Magento\Customer\Model\Session" session. After Login I need to add a custom array to the current customer session. how can i add a custom data to magento customer session? please help me with your valuable answer.

Best Answer

You need to create customer_login event observer for set value in customer session after login

1) Create events.xml

app/code/Vendor/Module/etc/events.xml

<?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="customer_login_observer" instance="Vendor\Module\Observer\CustomerLogin" />
    </event>
</config>

2) After this file, you need to create your observer file

app/code/Vendor/Module/Observer/CustomerLogin.php

<?php

namespace Vendor\Module\Observer;

use Magento\Framework\Event\ObserverInterface;

class CustomerLogin implements ObserverInterface
{
    protected $customerSession;

    public function _construct(
        \Magento\Customer\Model\Session $customerSession
    ) {
        $this->customerSession = $customerSession;
    }   

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $customer = $observer->getEvent()->getCustomer(); //Get customer object
        $myArray = array('value1','value2');
        $setValye = $this->customerSession->setMyValue($myArray); //set value in customer session
        $getValue = $this->customerSession->getMyValue(); //Get value from customer session
        print_r($getValue);
        exit;
    }
}

Now run this commands:

php bin/magento cache:flush

php bin/magento setup:di:compile

Related Topic