As Magento 2 store owner, you may want to treat logged in and non-logged in customers differently. For example, you may want to offer exclusive features or discounts to logged in customers only. To implement this, you first need to confirm whether a Magento 2 customer is logged in or not?
Methods To Check If A Customer Is Logged-In In Magento 2
There are 2 ways you can check this. By injecting class and by using object manager. Although the 2nd method (object manager) is not recommended, it’s still used as an alternative.
Method 1: By Injecting Class (Dependency Injection)
In this method, first, you need to inject the following class in the constructor method:
/Magento/Customer/Model/Session
protected $_session;
public function __construct(
...
\Magento\Customer\Model\Session $session,
...
) {
...
$this->_session