Filament: Form with Custom Fields

Demonstrates how to use dynamic custom fields in Filament Forms, similar to WordPress.

22-form-custom-fields

Get the Source Code:

How it works

The main logic here lives in our CustomerResource classes form() method:

  • We are using a Repeater to create a dynamic number of fields
  • We are using a Pivot model to enable our Many-to-Many relationship between Customer and Field models
  • We are turning off fields as soon as they are selected to prevent duplicates

Here's how that looks in our code:

app/Models/Field.php

class Field extends Model
{
protected $fillable = [
'name',
];
}

app/Models/CustomerField.php

// ...
class CustomerField extends Pivot
{
public function customer(): BelongsTo
{
return $this->belongsTo(Customer::class);
}
 
public function field(): BelongsTo
{
return $this->belongsTo(Field::class);
}
}

Remember that this Model is required for the Repeater to work, as it's a Many-to-Many relationship. That's a Filament requirement.

app/Models/Customer.php

class Customer extends Model
{
use HasFactory;
 
protected $fillable = [
'name',
'email',
'phone',
];
 
// We can access the many to many relationship with the fields() method
public function fields(): BelongsToMany
{
return $this->belongsToMany(Field::class)->withPivot('value');
}
 
// But Filament uses this to fill the repeater
public function customerFields(): HasMany
{
return $this->hasMany(CustomerField::class);
}
}

And finally, here's how we are building the form itself:

app/Filament/Resources/CustomerResource.php

public static function form(Form $form): Form
{
return $form
->schema([
// We made a Section with our customer fields, nothing special
Forms\Components\Section::make('Customer Details')
->schema([
Forms\Components\TextInput::make('name')
->required()
->maxLength(255),
Forms\Components\TextInput::make('email')
->email()
->required()
->maxLength(255),
Forms\Components\TextInput::make('phone')
->required()
->maxLength(255),
])
->columns(),
// Here's the Repeater with our custom fields
Forms\Components\Repeater::make('fields')
 
// ...
The FULL tutorial is available after the purchase: in the Readme file of the official repository you would get invited to.
Get the Source Code: All 50 Premium Examples for $99 Only Form Examples for $39