diff --git a/src/Traits/HasCategories.php b/src/Traits/HasCategories.php index d937d44..f274862 100644 --- a/src/Traits/HasCategories.php +++ b/src/Traits/HasCategories.php @@ -134,6 +134,40 @@ trait HasCategories $this->categories()->sync($categories); } + /** + * Sync categories by name + * + * @param array $categories + */ + public function syncCategoriesByNames(array $categories): void + { + $categoryIds = []; + + foreach ($categories as $name) { + $category = config('shop.models.product_category')::firstOrCreate(['name' => $name]); + $categoryIds[] = $category->id; + } + + $this->categories()->sync($categoryIds); + } + + /** + * Sync categories by slug + * + * @param array $categories + */ + public function syncCategoriesBySlugs(array $categories): void + { + $categoryIds = []; + + foreach ($categories as $slug) { + $category = config('shop.models.product_category')::firstOrCreate(['slug' => $slug]); + $categoryIds[] = $category->id; + } + + $this->categories()->sync($categoryIds); + } + /** * Attach or create a category by name. */