$categories * @return EloquentCollection */ public function build(EloquentCollection $categories): EloquentCollection { if ($categories->isEmpty()) { return new EloquentCollection; } $rootParentId = $this->resolveRootParentId($categories); $categories->linkNodes(); /** @var EloquentCollection $tree */ $tree = $categories ->filter(static fn (Category $category): bool => $category->getParentId() === $rootParentId) ->values(); return $this->removeParentRelationships($tree); } /** * @return EloquentCollection */ public function buildAccessibleTo(mixed $user): EloquentCollection { return $this->build(CategoryAccess::getFilteredTreeFor($user)); } /** * @return EloquentCollection */ public function buildThreadDestinations(): EloquentCollection { return $this->build(Category::query()->threadDestinations()->get()); } /** * @param EloquentCollection $categories */ public function hideManageColumns(EloquentCollection $categories): void { $categories->each(function (Category $category): void { $category->makeHidden(['_lft', '_rgt', 'thread_count', 'post_count']); if ($category->relationLoaded('children') && $category->children->isNotEmpty()) { /** @var EloquentCollection $children */ $children = $category->children; $this->hideManageColumns($children); } }); } /** * @param EloquentCollection $categories */ private function resolveRootParentId(EloquentCollection $categories): int|string|null { $rootParentId = null; $lowestLeft = null; foreach ($categories as $category) { $left = $category->getLft(); if ($lowestLeft === null || ($left !== null && $left < $lowestLeft)) { $lowestLeft = $left; $rootParentId = $category->getParentId(); } } return $rootParentId; } /** * @param EloquentCollection $categories * @return EloquentCollection */ private function removeParentRelationships(EloquentCollection $categories): EloquentCollection { $categories->each(function (Category $category): void { $category->setRelation('parent', null); if (! $category->relationLoaded('children')) { return; } /** @var EloquentCollection $children */ $children = $category->children; $category->setRelation('children', $this->removeParentRelationships($children)); }); return $categories; } }