Filament: Save Form Data in Multiple DB Tables

2024-11-22

It's common to see forms that can create multiple table rows simultaneously. For example, a User profile with Billing Details:

This should result in two records in the database:

  • users table - with user's information
  • billing_details table - with the user's billing details

Filament supports this out of the box. Just not by modifying code, but rather by specific form:

public static function form(Form $form): Form
{
return $form
->schema([
Forms\Components\TextInput::make('name')
->required(),
Forms\Components\TextInput::make('email')
->email()
->required(),
Forms\Components\DateTimePicker::make('email_verified_at'),
Forms\Components\TextInput::make('password')
->password()
->required(),
Forms\Components\Fieldset::make('billingDetail')
->label('Billing Details')
->relationship('billingDetail')
->schema([
Forms\Components\TextInput::make('name'),
Forms\Components\TextInput::make('address'),
Forms\Components\TextInput::make('city'),
Forms\Components\TextInput::make('postal_code'),
Forms\Components\TextInput::make('phone'),
Forms\Components\TextInput::make('email'),
Forms\Components\TextInput::make('country'),
])
]);
}

In this form, we have created:

  • A fieldset for Billing Details
  • Told Filament that this Fieldset is a relationship to billingDetail
  • Filament understands this and will call $user->billingDetail()->create($data)
  • $data will come from the schema of our Fieldset

That's it! This is flexible when it comes to creating multiple related records at once.

A few of our Premium Examples: