Creating and updating pivot table with attributes in the relationmanager
I created a IngredientsRelationManager inside the RecipeResource: i see the table fine and get the add new ingredient button and modal:
for some reason it is creating a record in the Ingredients table instead of the pivot recipe_ingredient table.
pivot relationships are
Recipe Model:
public function ingredients()
{
return $this->belongsToMany(Ingredient::class, 'recipe_ingredient', 'recipe_id', 'ingredient_id')
->withPivot('quantity', 'unit');
}
Ingredients Model:
public function recipes()
{
return $this->belongsToMany(Recipe::class, 'recipe_ingredient', 'recipe_id', 'ingredient_id')
->withPivot('quantity', 'unit');
}
code:
{
protected static string $relationship = 'ingredients';
public function form(Form $form): Form
{
$ingredients = Ingredient::all()->pluck('name', 'id')->toArray();
return $form
->schema([
Forms\Components\Select::make('ingredient_id')
->placeholder('Select Ingredients')
->searchable()
->columnSpan(1)
->required()
->options($ingredients),
Forms\Components\TextInput::make('quantity')->default(1),
Forms\Components\TextInput::make('unit')->default('1'),
]);
}
10 Replies
for some reason it is creating a record in the Ingredients table instead of the pivot recipe_ingredient table.Are you using
AttachAction
?Nope, simple pivot with attributes, it creates a new ingredient in the ingredients table and then inserts into the recipe_ingredient as well
Ok, maybe I'm missing a bit of context but make sure to give this section a read:
https://filamentphp.com/docs/3.x/panels/resources/relation-managers#attaching-and-detaching-records
Will dođź‘Ť
great that is what I neededđź‘Ť , question how can I rename the "Attach/Detach" buttons/links? I tried like this :->headerActions([
// ...
Tables\Actions\AttachAction::make('Add Ingredient')
->preloadRecordSelect()
->form(fn (AttachAction $action): array => [
$action
->getRecordSelect()
->placeholder('Select an Ingredient'),
Forms\Components\TextInput::make('quantity')->required(),
Forms\Components\TextInput::make('unit')->required()]),
])
You can call
->label('My Label')
on each actiongr8 thanks!
what defines this modal button? "Attach & attach another"
->attachAnother(false)
if you want to disablehi, I am trying to change the attachaction and add a function that works on the create/edit for recipe_ingredient, I tried using the Createaction :CreateAction::make()
->mutateFormDataUsing(function (array $data): array {
$data['user_id'] = auth()->id();
return $data;
})
according to the docs but it creates a new ingredient and doesnt affect the pivot table
Did you configure
withPivot()
on your model relationships?