Save relationship with pivot attributes/columns

I need some help. How can i conditionally fill the pivot attribute/column when creating a Model from Select field using the createOptionForm. here is what i am trying.
// Relationship defined in Model
public function tags(): MorphToMany
{
return $this->morphToMany(Tag::class, 'taggable')
->wherePivot('is_approved', false);
}

// Select input in a resource form.
Select::make('tags')
->relationship('tags', 'name')
->multiple()
->createOptionForm([
TextInput::make('name'),
])
// Relationship defined in Model
public function tags(): MorphToMany
{
return $this->morphToMany(Tag::class, 'taggable')
->wherePivot('is_approved', false);
}

// Select input in a resource form.
Select::make('tags')
->relationship('tags', 'name')
->multiple()
->createOptionForm([
TextInput::make('name'),
])
When the relationship is saved, I need to set the is_approved column set to true/false based on a condition. Thanks.
4 Replies
Mansoor Khan
Mansoor KhanOP2y ago
Also, i need to filter the Select options based on the pivot condition. I have tried to chain following method on Select field but it does not work:
->saveRelationshipsUsing(
fn ($record, $tags) => $record
->tags()
->syncWithPivotValues($tags, ['is_category' => false])
)
->saveRelationshipsUsing(
fn ($record, $tags) => $record
->tags()
->syncWithPivotValues($tags, ['is_category' => false])
)
Dan Harrin
Dan Harrin2y ago
try $state instead of $tags
Mansoor Khan
Mansoor KhanOP2y ago
Hey Dan, I searched for saveRelationshipsUsing and found your helpful reply on a post. This is what worked for me:
->relationship('tags', 'name', fn (Builder $query) => $query->where('is_approved', false))
->saveRelationshipsUsing(static function (Select $component, $state) {
$component->getRelationship()->syncWithPivotValues($state, ['is_approved' => false]);
});
->relationship('tags', 'name', fn (Builder $query) => $query->where('is_approved', false))
->saveRelationshipsUsing(static function (Select $component, $state) {
$component->getRelationship()->syncWithPivotValues($state, ['is_approved' => false]);
});
Thanks a ton Dan! I love you!
Dan Harrin
Dan Harrin2y ago
no worries :) just remember to be careful with those parameter names because we allow you to use parameters in any order to get what you need, we are strict on the names.
Want results from more Discord servers?
Add your server