There are two ways by which you can check if a customer is logged in or not:
1) By using Object Manager
It is always a bad practice to use ObjectManager directly.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
if($customerSession->isLoggedIn()) {
// customer login action
}
2) By Injecting Class (Dependency Injection)
As said earlier, it is one of the worst practices to use the ObjectManager directly. Therefore an alternate way to check if a user is logged in or not is by using the following code in any class except the template files:
You first need to inject the following class in your constructor:
/Magento/Customer/Model/Session
protected $_session;
public function __construct(
...
\Magento\Customer\Model\Session $session,
...
) {
...
$this->_session = $session;
...
}
Then you need to use Magento\Customer\Model\Session::isLoggedIn() to check if the customer is logged in or not.
if ($this->_session->isLoggedIn()) {
// Customer is logged in
} else {
// Customer is not logged in
}