public function syncCategories($categories, bool $detaching = true)
{
// Find categories
$categories = $this->prepareCategoryIds($categories);
// Sync model categories
$this->categories()->sync($categories, $detaching);
return $this;
}
public function attachCategories($categories)
{
return $this->syncCategories($categories, false);
}
protected function prepareCategoryIds($categories): array
{
// Convert collection to plain array
if ($categories instanceof BaseCollection && is_string($categories->first())) {
$categories = $categories->toArray();
}
// Find categories by slug, and get their IDs
if (is_string($categories) || (is_array($categories) && is_string(array_first($categories)))) {
$categories = app('rinvex.categories.category')->whereIn('slug', $categories)->get()->pluck('id');
}
if ($categories instanceof Model) {
return [$categories->getKey()];
}
if ($categories instanceof Collection) {
return $categories->modelKeys();
}
if ($categories instanceof BaseCollection) {
return $categories->toArray();
}
return (array) $categories;
}