I want to check if a user is logged in.
Because I need to access customer-specific information.
Thanks for your help.
I want to check if a user is logged in.
Because I need to access customer-specific information.
Thanks for your help.
You can check this with
class MyClass
{
protected $customerSession;
public function __construct(\Magento\Customer\Model\Session $customerSession) {
$this->customerSession = $customerSession;
}
public isCustomerLoggedIn() {
return $this->_customerSession->isLoggedIn();
}
}
You can do this by making this following Code in your .phtml file:
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->create("Magento\Customer\Model\Session");
$contractAddress = $block->getContractAddress();
if($customerSession->isLoggedIn()) {
//Your Code
}
?>
public function __construct( \Magento\Customer\Model\Session $customerSession ) { $this->customerSession = $customerSession; }
– Rahul Anand Aug 14 '19 at 09:53You can use the __construct() DI method to initialize your API interface and call the methods to do some operations. Calling API method will call model's method as implementation is mentioned in di.xml files for all modules.
– Rahul Anand Aug 14 '19 at 09:58Try This
use Magento\Customer\Model\Customer;
use Magento\Customer\Model\CustomerFactory;
use Magento\Customer\Model\Session;
/**
* Class Index
*/
class Index extends \Magento\Framework\App\Action\Action
{
/**
* @param \Magento\Framework\App\Action\Context
* @param Customer
*/
public function __construct(
\Magento\Framework\App\Action\Context $context,
Session $customerSession,
) {
$this->customerSession = $customerSession;
parent::__construct($context);
}
public function execute()
{
if ($this->customerSession->isLoggedIn()) {
$this->messageManager->addWarning('User is loggedIn');
return $resultRedirect;
}
} else {
$this->messageManager->addWarning('User Not loggedIn');
return $resultRedirect;
}
}
}