Magento 2 – Check If Customer is Subscribed to Newsletter

customermagento-2.1magento2modulenewsletter

I am developing this custom xml export/import. In magento 2 how can I check if a customer is subscribed to newsletter? Right now I am loading the customer factory.

\Magento\Framework\App\ObjectManager::getInstance()->create('Magento\Customer\Model\Customer');

But this does not give information about newsletter is there another model I have to load?

Best Answer

First inject the \Magento\Newsletter\Model\Subscriber class in your constructor:

protected $_subscriber;

public function __construct(
    ...
    \Magento\Newsletter\Model\Subscriber $subscriber
    ...
){
    ...
    $this->_subscriber= $subscriber;
    ...
}

Then you have two possible cases

Assuming your have the customer email

Then in your code you can call the following code to check whether or not the customer is subscribed to the newsletter:

$checkSubscriber = $this->_subscriber->loadByEmail($customerEmail);

if ($checkSubscriber->isSubscribed()) {
    // Customer is subscribed
} else {
    // Customer is not subscribed
}

Assuming you have the customer id

You can call the following code:

$checkSubscriber = $this->_subscriber->loadByCustomerId($customerId);

if ($checkSubscriber->isSubscribed()) {
    // Customer is subscribed
} else {
    // Customer is not subscribed
}
Related Topic