Search code examples
phpshopifyshopwareshopware6

Check if a category exists Shopware 6


Check if a category existsyour text

I have such code

 $categoryService = $this->container->get('category.repository');
    $newCategory = [
            'name' => 'Profi-Shop',
            'parentId' => null,
            'customFields' => [
        ],
    ];

    $categoryService->create([$newCategory], $context->getContext());

It is executed every time. How to execute it only if there is no such category


Solution

  • You need to check if your category exists prior creating it. If it does, then just skip creation step:

    use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
    use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
    
    $categoryService = $this->container->get('category.repository');
    $newCategoryName = 'Profi-Shop';
    
    // Search for the category first
    $criteria = new Criteria();
    $criteria->addFilter(new EqualsFilter('name', $newCategoryName));
    $existingCategory = $categoryService->search($criteria, $context->getContext());
    
    // Create it if there's no match found:
    if ($existingCategory->getTotal() === 0) {
        $newCategory = [
            'name' => $newCategoryName,
            'parentId' => null,
            'customFields' => [],
        ];
    
        $categoryService->create([$newCategory], $context->getContext());
    }