diff --git a/src/SelectTree.php b/src/SelectTree.php index aca66f2..737cece 100644 --- a/src/SelectTree.php +++ b/src/SelectTree.php @@ -160,14 +160,29 @@ protected function setUp(): void protected function buildTree(): Collection { - // Start with two separate query builders - $nullParentQuery = $this->getQuery()->clone()->where($this->getParentAttribute(), $this->getParentNullValue()); - $nonNullParentQuery = $this->getQuery()->clone()->whereNot($this->getParentAttribute(), $this->getParentNullValue()); - - // If we're not at the root level and a modification callback is provided, apply it to null query + // If we have a modifyQueryUsing callback, use a single query approach + // This handles filtered queries that might not fit the standard null/non-null parent structure if ($this->modifyQueryUsing) { - $nullParentQuery = $this->evaluate($this->modifyQueryUsing, ['query' => $nullParentQuery]); + $query = $this->getQuery()->clone(); + $query = $this->evaluate($this->modifyQueryUsing, ['query' => $query]); + + if ($this->withTrashed) { + $query->withTrashed($this->withTrashed); + } + + $results = $query->get(); + + // Store results for additional functionality + if ($this->storeResults) { + $this->results = $results; + } + + return $this->buildTreeFromResults($results); } + + // Original logic for non-filtered queries + $nullParentQuery = $this->getQuery()->clone()->where($this->getParentAttribute(), $this->getParentNullValue()); + $nonNullParentQuery = $this->getQuery()->clone()->whereNot($this->getParentAttribute(), $this->getParentNullValue()); // If we're at the child level and a modification callback is provided, apply it to non null query if ($this->modifyChildQueryUsing) { @@ -223,10 +238,23 @@ private function buildTreeFromResults($results, $parent = null): Collection // Recursively build the tree starting from the root (null parent) $rootResults = $resultMap[$parent] ?? []; - foreach ($rootResults as $result) { - // Build a node and add it to the tree - $node = $this->buildNode($result, $resultMap, $disabledOptions, $hiddenOptions); - $tree->push($node); + + // If we have no root results but we have results, and we're using modifyQueryUsing, + // it means the query was filtered and might not have proper root items. + // In this case, show all results as root items to prevent empty trees. + if (empty($rootResults) && !empty($results) && $this->modifyQueryUsing) { + foreach ($results as $result) { + // Build a node and add it to the tree + $node = $this->buildNode($result, $resultMap, $disabledOptions, $hiddenOptions); + $tree->push($node); + } + } else { + // Normal tree building - only show items that are actually root items + foreach ($rootResults as $result) { + // Build a node and add it to the tree + $node = $this->buildNode($result, $resultMap, $disabledOptions, $hiddenOptions); + $tree->push($node); + } } return $tree;