Magento 2 Logout Customer Programmatically


Magento 2 Logout Customer Programmatically– Sometimes we need to logout customer programmatically based upon some condition or validation. Here in this article we are going to explain how you can logout customer from block, controller, model, observer or anywhere.


Magento 2 Logout Customer Programmatically Example

You can use object manager to logout customer session simply as below –

Magento 2 Logout Customer Programmatically Example:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->create('Magento\Customer\Model\Session');
if($customerSession->isLoggedIn()) {
$customerSession->_logout();
echo "Logged Out Successfully!";
}

The above example will logout the current customer session.


Advertisements

User Ans/Comments

1 exception(s): Exception #0 (InvalidArgumentException): Invalid method Magento\Customer\Model\Session\Interceptor::_logout(Array ( ) )Exception #0 (InvalidArgumentException): Invalid method Magento\Customer\Model\Session\Interceptor::_logout(Array ( ) ) #0 /home/devtheretailinsi/public_html/var/generation/Magento/Customer/Model/Session/Interceptor.php(336): Magento\Framework\Session\SessionManager->__call('_logout', Array) #1 /home/devtheretailinsi/public_html/app/code/Retailinsights/DemoTry/Observer/CustomerLogoutObserver.php(46): Magento\Customer\Model\Session\Interceptor->__call('_logout', Array) #2 /home/devtheretailinsi/public_html/vendor/magento/framework/Event/Invoker/InvokerDefault.php(73): Retailinsights\DemoTry\Observer\CustomerLogoutObserver->execute(Object(Magento\Framework\Event\Observer))
 kaushik

Add Comment

📖 Read More