I want to create a duplicate product using the product id programmatically. I have tried many solutions but have not had success. How to do it?
2 Answers 2
Let's create a class that would handle this:
namespace .....
class ProductClone
{
private \Magento\Catalog\Model\Product\Copier $copier;
private \Magento\Catalog\Api\ProductRepositoryInterface $repository;
public function __construct(
\Magento\Catalog\Model\Product\Copier $copier,
\Magento\Catalog\Api\ProductRepositoryInterface $repository
) {
$this->copier = $copier;
$this->repository = $repository;
}
public function duplicate(int $productId): \Magento\Catalog\Api\Data\ProductInterface
{
$product = $this->repository->getById($productId);
return $this->copier->copy($product);
}
}
Now you just need to include this class as a dependency in your custom logic and call the duplicate method with your product id as a parameter.
Watch out for typos in the code above, I didn't test it.
Copying products programmatically in Magento 2 can be achieved using the native approach, which utilizes Magento's built-in functionality in the Admin panel for copying products. To do this, you can take advantage of the Magento\Catalog\Controller\Adminhtml\Product\Duplicate controller along with the Magento\Catalog\Model\Product\ProductCopier class, which simplifies the process for you.
Below is an example of how you can implement the product duplication:
/** @var \Magento\Catalog\Model\Product\Copier $productCopier */
/** @var \Magento\Catalog\Api\ProductRepositoryInterface $productRepository */
$product = $productRepository->get('SKU');
$duplicatedProduct = $productCopier->copy($product);
In the code above, we use the ProductRepositoryInterface to load the product with the specified SKU you want to duplicate. Then, we pass that product instance to the ProductCopier to create a new duplicated product.
Explore related questions
See similar questions with these tags.