Skip to content

Instantly share code, notes, and snippets.

@Z3d0X
Last active September 18, 2023 08:23
Show Gist options
  • Save Z3d0X/e53c8db4ad425b0bb4987e23ce686548 to your computer and use it in GitHub Desktop.
Save Z3d0X/e53c8db4ad425b0bb4987e23ce686548 to your computer and use it in GitHub Desktop.
Repeater / Builder Unique
<?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.");
}
};
})
<?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