I need to integrate a functionality where when a user clicks add to cart it should check whether he is a logged in customer or not. If he is a logged in customer the product should be added in cart. Else it should redirect to Login page after logging in the products to be added automatically. If anyone has any idea pls share.

  • Have you find any solution for this?, if yes please share with me also, as I also required same functionality. Aug 30, 2019 at 13:49

2 Answers 2

  1. listen to the event sales_quote_add_item
  2. check if the customer is logged in
  3. if not, rdirect to login page

Method 1:

You need to create an observer (controller_action_predispatch_checkout_cart_add) to check the customer is logged in or not. If not, you need to redirect to login page.

Example: redirect to login page from the observer, add the customer login check logic from here.

namespace Vendor\ModuleName\Observer;

use Magento\Framework\Event\ObserverInterface;

class CheckLoginObserver implements ObserverInterface
    protected $redirect;
    public function __construct(
        \Magento\Framework\App\Response\RedirectInterface $redirect
    ) {
        $this->redirect = $redirect;

     * Redirect to login page
     * @param \Magento\Framework\Event\Observer $observer
     * @return $this
    public function execute(\Magento\Framework\Event\Observer $observer)
        /** @var \Magento\Framework\App\Action\Action $controller */
        $controller = $observer->getControllerAction();
        $this->redirect->redirect($controller->getResponse(), 'customer/account/login');

        return $this;

Method 2:

If you want to change globally including API request, you need to add before plugin for Magento\Checkout\Model\Cart:addProduct($productInfo, $requestInfo = null) and repeat the same thing what you did in the observer.

Your Answer

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

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