Last active
September 18, 2023 08:23
-
-
Save Z3d0X/e53c8db4ad425b0bb4987e23ce686548 to your computer and use it in GitHub Desktop.
Repeater / Builder Unique
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//Use on a field inside a builder | |
->rule(function ( | |
Component $component, | |
mixed $state, | |
) { | |
return function (string $attribute, $value, Closure $fail) use ($component, $state) { | |
/** @var array<string,array<string,mixed>> */ | |
$siblings = $component->getContainer()->getParentComponent()?->getState(); | |
if (blank($siblings)) { | |
return; | |
} | |
$componentKey = (string) Str::of($component->getStatePath()) | |
->beforeLast(".data.{$component->getName()}") | |
->afterLast('.'); | |
$isDuplicate = collect($siblings) | |
->reject(fn ($sibling, $key) => $key == $componentKey) | |
->pluck("data.{$component->getName()}") | |
->contains($state); | |
if ($isDuplicate) { | |
$fail("{$component->getLabel()} must be unique."); | |
} | |
}; | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//Use on a field inside a repeater | |
->rule(function ( | |
Field $component, | |
mixed $state, | |
) { | |
return function (string $attribute, $value, Closure $fail) use ($component, $state) { | |
/** @var array<string,array<string,mixed>> */ | |
$siblings = $component->getContainer()->getParentComponent()?->getState(); | |
if (blank($siblings)) { | |
return; | |
} | |
$componentKey = (string) Str::of($component->getStatePath()) | |
->beforeLast(".{$component->getName()}") | |
->afterLast('.'); | |
$isDuplicate = collect($siblings) | |
->reject(fn ($sibling, $key) => $key == $componentKey) | |
->pluck($component->getName()) | |
->contains($state); | |
if ($isDuplicate) { | |
$fail("{$component->getLabel()} field must be unique."); | |
} | |
}; | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment