Unique selections on relationship repeater

I am using a repeater to create BelongsToMany relationships between two models. I would like to ensure the relationship to only exists once. Is there an easy way to accomplish this through the form builder?
2 Replies
roombroom
roombroomOP2y ago
That does appear to be a tutorial for what I'm looking for; ugh, paywalls :/ This is the solution I came up with -- It's "messy" but it works for my purposes:
Forms\Components\Repeater::make('itemCategories')
->relationship()
->schema([
Forms\Components\Select::make('category_id')
->label('Category')
->options(function ($state, Closure $get) {
$selectedCategories = array_unique(array_column($get('../../itemCategories'), 'category_id'));
$selectedCategories = array_map(fn($a): int => intval($a), $selectedCategories);
$selectedCategories = array_filter($selectedCategories, function ($a) use ($state) {
return !($a === 0 || $a == $state);
});
return Category::query()->whereNotIn('id', $selectedCategories)->pluck('name', 'id');
})
->required()
->reactive(),
])
Forms\Components\Repeater::make('itemCategories')
->relationship()
->schema([
Forms\Components\Select::make('category_id')
->label('Category')
->options(function ($state, Closure $get) {
$selectedCategories = array_unique(array_column($get('../../itemCategories'), 'category_id'));
$selectedCategories = array_map(fn($a): int => intval($a), $selectedCategories);
$selectedCategories = array_filter($selectedCategories, function ($a) use ($state) {
return !($a === 0 || $a == $state);
});
return Category::query()->whereNotIn('id', $selectedCategories)->pluck('name', 'id');
})
->required()
->reactive(),
])
Want results from more Discord servers?
Add your server