In this tutorial, Today I will explain to how to check customer is logged in or not in Magento 2. When we develop any functionality based on customer is logged in or not at that time, we need to check that customer is logged in or not. Sometimes, we need to add restriction like if customer is logged in then only they can use this functionality. At that time, this code is useful to check customer logged in data.
You can check customer is logged in or not using \Magento\Framework\App\Http\Context class. For that you need to inject class in your construct.. So, Let’s check the below code :
You may also like this :
- How to Check if Attribute is Swatch Attribute in Magento 2?
- Magento 2 : Add “Use Default Value” Checkbox in UI Form
Steps of check customer is logged in or not in Magento 2 :
First, You need to use this below code in your block file. After that, you can call isCustomerLoggedIn() function to check customer logged in or not.
<?php
/**
* Created By : Rohan Hapani
*/
namespace RH\Helloworld\Block;
class CustomerDetails extends \Magento\Framework\View\Element\Template
{
/**
* @var \Magento\Framework\App\Http\Context
*/
protected $httpContext;
/**
* @param \Magento\Framework\View\Element\Template\Context $context
* @param \Magento\Framework\App\Http\Context $httpContext
* @param array $data
*/
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);
}
/**
* @return boolean
*/
public function isCustomerLoggedIn() {
return $this->httpContext->isLoggedIn();
}
}
In addition, you can use like this inside template file :
/**
* Created By : Rohan Hapani
*/
$isLoggedin = $block->isCustomerLogin();
if($isLoggedin) {
// customer is logged in
} else {
// customer is not logged in
}
If you want to check in javascript file, you can also check in javascript using this below solution. You can add this below code in your javascript file and after that retrieve information about customer also. customer.isLoggedIn(); value will be return boolean value.
Steps of check customer is logged in or not in js in Magento 2 :
/**
* Created By : Rohan Hapani
*/
define([
'ko',
'jquery',
'uiComponent',
'Magento_Customer/js/model/customer'
], function (
ko,
$,
Component,
customer
) {
'use strict';
return Component.extend({
/**
* Check if customer is logged in
*
* @return {boolean}
*/
isLoggedIn: function () {
return customer.isLoggedIn();
}
});
});
After that, Add this code in your JS file, You need to deploy JS file.
That’s it !!!
Now, you just need to remove generated and clean cache.
I hope this blog is easy to understand about how to check customer is logged in or not in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution.
Stay Safe and Stay Connected !!