2

Is there a way where in a check through a .phtml block to see that the customer is logged in, and If so, automatically log them out - please no observers or modules.

I feel confident that I've seen a solution that talked about auto log out somewhere vaguely, but I am unable to find this.

Vrajesh Patel
  • 1,964
  • 2
  • 12
  • 28
GuitarKat
  • 113
  • 2
  • 11

2 Answers2

2

Try this:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->create('Magento\Customer\Model\Session');
$customerSession->logout();

source

Jaimin Sutariya
  • 11,140
  • 5
  • 34
  • 70
Idham Choudry
  • 2,818
  • 3
  • 38
  • 62
  • I read that using object manager from a .phtml isn't that great for reasons - I forget what they are. I see people warning against doing that in other answers. However, thank you for your help. Is there another solution that may use this not as directly?

    https://magento.stackexchange.com/questions/117098/to-use-or-not-to-use-the-objectmanager-directly

    – GuitarKat Feb 28 '20 at 14:33
0

In your block class:

public function __construct(
    Context $context,
    \Magento\Customer\Model\Session $customerSession
) {
    parent::__construct($context);
    $this->customerSession = $customerSession;
}
public function logoutCustomer()
{
    $customerId = $this->customerSession->getId();
    if ($this->customerSession->isLoggedIn()) {
        $this->customerSession->logout()->setBeforeAuthUrl($this->redirect->getRefererUrl())->setLastCustomerId($customerId);
        return "Customer logout successfully";
    }
    return false;
}

Call function in your phtml file:

<?php $block->logoutCustomer(); ?>
  • Hello there! I have a question to your solution or anyone who may have an idea about what block class means exactly. I noticed you used a block class... where would that be located? I have my phtml referenced in a .phtml - I do like how you're not using objectManager directly. – GuitarKat Feb 28 '20 at 14:40