Magento 2 – How to Logout Customer from Controller

controllerscustomcustomerlogoutmagento2

In Magento 2, I want to write a custom controller. Whenever anyone tries to call the controller

URL (http://mymagento.com/mycontroller/index/index).

It should redirect to this controller an event dispatch should trigger to logout from Magento 2 site.

Best Answer

Please try with below code.

        <?php
public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Customer\Model\Session $customerSession
) {
    $this->redirect = $context->getRedirect();
    $this->customerSession = $customerSession;
}

public function customerLogout() {
    $customerId = $this->customerSession->getId();
    if($customerId) {
        $this->customerSession->logout()
             ->setBeforeAuthUrl($this->redirect->getRefererUrl())
             ->setLastCustomerId($customerId);
        return "logout successfully";
    } 
}

than push basic commands.

I hope its work for you.

Related Topic