Update Customer Group in Magento 2 by Customer id for the customer.
If you want to change existing customer groups to different customer groups for the Customer you can do it using Customer Repository interface API.
To Retrieve the Customer Object by customer id, set Group id using the setGroupId() method to the return object and save the customer object to update group id.
<?php namespace Jesadiya\GroupId\Model; use Magento\Framework\Exception\LocalizedException; use Magento\Customer\Api\CustomerRepositoryInterface; use Psr\Log\LoggerInterface; class UpdateCustomerGroup { /** * @var LoggerInterface */ private $logger; /** * @var CustomerRepositoryInterface */ private $customerRepository; public function __construct( LoggerInterface $logger, CustomerRepositoryInterface $customerRepository ) { $this->logger = $logger; $this->customerRepository = $customerRepository; } /** * Save Customer group * @param int $customerId * @param int $groupId * @return void */ public function updateCustomerGroup(int $customerId, int $groupId): void { $customer = $this->getCustomerById($customerId); if ($customer) { try { $customer->setGroupId($groupId); $this->customerRepository->save($customer); } catch (LocalizedException $exception) { $this->logger->error($exception); } } } /** * Get Customer By Id * @param int $customerId * @return CustomerInterface|null */ private function getCustomerById(int $customerId): ?CustomerInterface { try { $customer = $this->customerRepository->getById($customerId); } catch (LocalizedException $exception) { $customer = null; $this->logger->error($exception); } return $customer; } }
Call method with a required parameter,
$customerId = 1; $groupId = 3; $this->updateCustomerGroup($customerId, $groupId);
Follow the given code snippet to work as expected for the updated customer group.