Magento 2 – Get Category Collection From Product ID

categorycollection;magento2

How can I get category collection data from product ID? I have tried using the following way but it's not working for me.

$product = $this->_productFactory->create()->getCollection()->load($pid);
$cats = $product->getCategoryIds();
if(count($cats) ){
    $firstCategoryId = $cats[0];
    $_category = $this->_categoryFactory->create()->getCollection()->load($firstCategoryId);
    return $_category->getName();
}

Best Answer

$product = $this->_productFactory->create()->load($pid);
$cats = $product->getCategoryIds();
if(count($cats) ){
    $firstCategoryId = $cats[0];
    $_category = $this->_categoryFactory->create()->load($firstCategoryId);
    return $_category->getName();
}