Magento 2: Add Multiple Products To Cart Programmatically

Magento 2 Add Multiple Products to Cart

Adobe Commerce developers often require adding multiple products to the cart from the custom module. For example, developers need to add mass-action product lists and allow customers to add products to the cart with one click.

This post from SbDevBlg shows you the simplest way to add multiple products to a cart using the controller and service class.

I assume you have created a primary module with the necessary files, templates to show products with checkboxes, and a controller to handle the product form.

Add Multiple Products To Cart Programmatically

I have created a service class responsible for adding multiple products to the cart.

Create a service class inside your module’s services directory, ServiceClassName.php.

<?php
/**
 * @copyright Copyright (c) sbdevblog (http://www.sbdevblog.com)
 */

namespace VendorName\ModuleName\Services;

use Magento\Checkout\Model\Cart;

class ServiceClassName
{

    /**
     * @var Cart
     */
    private Cart $cart;

    /**
     * Constructor
     *
     * @param Cart $cart
     */
    public function __construct(Cart $cart)
    {
        $this->cart = $cart;
    }

    /**
     * Add Product To Cart
     *
     * @param array $productIds
     * @return void
     */
    public function addProductToCart(array $productIds):void
    {
        $this->cart->addProductsByIds($productIds);
        $this->cart->save();
    }
}

You may see that the above class has used Magento\Checkout\Model\Cart class, which has the addProductsByIds ($productsIds) method with a parameter of array type that belongs to the ids of specified products.

You may add several products by passing the ids of those products to the function addProductsByIds of \Magento\Checkout\Model\Cart class.

Also, you can check out the post to remove products from the cart programmatically.

Thanks for reading the post on adding multiple products to the cart programmatically.

You may download the source code, which I have shown as a list of simple products on the custom page, accessible from the top link, SbDeVBlog Products. That list allows customers to add multiple or single products to the cart.

Note: Please verify the code of this blog and the relevant git repository before using it in production.
sb dev blog adobe commece Magento 2

🙂 HAPPY CODING 🙂

One thought on “Magento 2: Add Multiple Products To Cart Programmatically

Leave a Reply

Your email address will not be published. Required fields are marked *