2

I need to check if category exist or not by category name.

I have try this with category name test but it does not work at the same time it does not throw any error

$category = $this->_objectManager->create('Magento\Catalog\Model\Category');

$cate = $category->getCollection()->addAttributeToFilter('name','test')->getFirstItem();

if (!isset($cate)) {
    echo "not exist";
} else {
    echo "already exist";
}

how to deal with check if category exist or not?

Thanks

2 Answers 2

1

use $cate->getId() it give false value when category does not exit

if (!$cate->getId()) {
    echo "not exist";
} else {
    echo "already exist";
}
3

please make change in if condition as below:

if ($cate->getSize() > 0) {
    echo "already exist";
} else {
    echo "not exist";
}

above code should give you the desired result..

And I would recommend you use Constructor Injection to get the collection rather than creating it into object manager...

hope this will work...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.