diff --git a/README.md b/README.md index d3b52f7..c527037 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,9 @@ SelectTree::make('category_id') // Set nodes as dependent ->independent(false) +// Set the parent's null value to -1, allowing you to use -1 as a sentinel value (default = null) +->parentNullValue(-1) + // Expand the tree with selected values ->expandSelected(false) diff --git a/src/SelectTree.php b/src/SelectTree.php index 7433fd2..8ce40ca 100644 --- a/src/SelectTree.php +++ b/src/SelectTree.php @@ -31,6 +31,8 @@ class SelectTree extends Field protected string $parentAttribute; + protected null|int|string $parentNullValue = null; + protected bool $clearable = true; protected bool $expandSelected = true; @@ -79,8 +81,11 @@ protected function setUp(): void }); } - private function buildTree(int $parent = null): array|Collection + private function buildTree($parent = null): array|Collection { + // Assign the parent's null value to the $parent variable if it's not null + $parent = $this->getParentNullValue() ?? $parent; + // Create a default query to retrieve related items. $defaultQuery = $this->getRelationship() ->getRelated() @@ -134,6 +139,13 @@ public function direction(string $direction): static return $this; } + public function parentNullValue(int|string $parentNullValue = null): static + { + $this->parentNullValue = $parentNullValue; + + return $this; + } + public function getRelationship(): BelongsToMany|BelongsTo { return $this->getModelInstance()->{$this->evaluate($this->relationship)}(); @@ -149,6 +161,11 @@ public function getParentAttribute(): string return $this->evaluate($this->parentAttribute); } + public function getParentNullValue(): null|int|string + { + return $this->evaluate($this->parentNullValue); + } + public function clearable(bool $clearable = true): static { $this->clearable = $clearable;