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. Jan 30, 2018 at 3:23
  • already declare in latest code still not working @KhoaTruongDinh Jan 30, 2018 at 3:51
  • Please update your question with the latest code. Jan 30, 2018 at 4:00
  • @KhoaTruongDinh updated Jan 30, 2018 at 4:03
  • 1
    Did you try to remove generation folder? Jan 30, 2018 at 4:34

1 Answer 1


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

  • 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. Jan 30, 2018 at 4:02
  • I have tried disabled all caching but still not working Jan 30, 2018 at 4:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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