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.

2

Try this:

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

source

| improve this answer | |
  • 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? magento.stackexchange.com/questions/117098/… – GuitarKat Feb 28 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(); ?>
| improve this answer | |
  • 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 at 14:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.