I am trying to intercept add to cart button.

What I intend to do:
If customer is not logged in, throw error message. Else if customer is logged in, add item to cart.

I did it in following way. I got the error message Cannot add to cart. as expector for customer that is not logged in. But I can't get user to add the product if the customer is logged in. I get the error message We can't add this item to your shopping cart right now..

What am I doing it wrong? Note that I can add the particular product to cart if i commented out the logic in this plugin.

============================================================================= Note updated code as advise. It seems like can't get customer session with following code. Everything works correctly if i commented out the customer session \Magento\Customer\Model\Session and related code to check if customer is log in.

use Magento\Framework\Exception\LocalizedException;

class Cart
    protected $session;

    public function __construct(
        \Magento\Customer\Model\Session $session
    ) {
        $this->session = $session;

    public function beforeAddProduct(
        \Magento\Checkout\Model\Cart $subject,
        $requestInfo) {
        if (!$this->session->isLoggedIn()) {
            throw new LocalizedException(__('Cannot add to cart.'));
            return [$productInfo, $requestInfo];
       return [$productInfo, $requestInfo];
  • Should declare protected $session variable. – Khoa TruongDinh Jan 30 '18 at 3:23
  • already declare in latest code still not working @KhoaTruongDinh – stackdisplay Jan 30 '18 at 3:51
  • Please update your question with the latest code. – Khoa TruongDinh Jan 30 '18 at 4:00
  • @KhoaTruongDinh updated – stackdisplay Jan 30 '18 at 4:03
  • 1
    Did you try to remove generation folder? – Khoa TruongDinh Jan 30 '18 at 4:34

For checking customer logged in or not, use Magento\Customer\Model\Session

|improve this answer|||||
  • Hi i upvoted your correction. That is a mistake i make in my code. But it seems that it can't get customer session. with Magento\Customer\Model\Session in the plugin. It hangs at "adding" once i make the changes. – stackdisplay Jan 30 '18 at 4:02
  • I have tried disabled all caching but still not working – stackdisplay Jan 30 '18 at 4:10

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.