If you Add Free Product in Cart When Add Perticular Product In cart.
So You Can Use Event Observer For Add Free Product in cart.
events.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="checkout_cart_product_add_after">
<observer name="add_free_product_to_cart" instance="Vendor\Checkout\Observer\AddFreeProductToCart" />
</event>
</config>
Observer:
AddFreeProductToCart.php
<?php
namespace Vendor\Checkout\Observer;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Checkout\Model\Session as CheckoutSession;
class AddFreeProductToCart implements ObserverInterface
{
protected $productRepository;
protected $checkoutSession;
public function __construct(
ProductRepositoryInterface $productRepository,
CheckoutSession $checkoutSession
) {
$this->productRepository = $productRepository;
$this->checkoutSession = $checkoutSession;
}
public function execute(Observer $observer)
{
$item = $observer->getEvent()->getData('quote_item');
$product = $item->getProduct();
if ($product->getSku() == '306081-0142') {
// Add the desired product (SKU '620001-01') to the cart
$productIdToAdd = '620001-01';
$productToAdd = $this->productRepository->get($productIdToAdd, false, null, true);
if ($productToAdd && $productToAdd->getId()) {
$quote = $this->checkoutSession->getQuote();
$productToAdd->setPrice(0);
$quote->addProduct($productToAdd);
$quote->collectTotals();
$quote->save();
}
}
}
}
When You Use This Event-Observer Then Solve Your Problem For Buy X Get Y Free Product..