Get Company id by company name programmatically in B2B Magento 2.

You can get company id by company name using B2B Magento 2.

You required Company name to fetch company id programmatically using Magento\Company\Api\CompanyRepositoryInterface interface.

<?php
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\Exception\LocalizedException;
use Magento\Company\Api\CompanyRepositoryInterface;

class Company
{
	 public function __construct(
        CompanyRepositoryInterface $companyRepository,
        SearchCriteriaBuilder $searchCriteriaBuilder
    ) {
        $this->companyRepository = $companyRepository;
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
    }

    /**
     * @param string $companyName
     * @return int|null
     * @throws LocalizedException
     */
    public function getCompanyId(string $companyName): ?int
    {
        $this->searchCriteriaBuilder->addFilter(
            'company_name',
            trim($companyName)
        );
        $companyData = $this->companyRepository->getList(
            $this->searchCriteriaBuilder->create()
        )->getItems();
        $companyId = null;
        if ($companyData) {
            foreach ($companyData as $company) {
                $companyId = (int)$company->getId();
            }
        }
        return $companyId;
    }
}

Call function from Class or template,

$companyName = “My Company”;
$companyId = $this->getCompanyId($companyName);

Output will be company id based on company name.