Filament PHP Repeater Forms

Filament PHP Repeater Forms

In modern web applications, forms often need to accommodate dynamic, repeatable data structures—think lists of addresses, multiple contact numbers, or an arbitrary number of product variants. Manually managing these variable-length collections can get messy quickly. Enter Filament PHP’s Repeater component: a clean, powerful way to add repeatable form sections in your Laravel admin panels. In this article, we’ll explore what the Repeater is, when to use it, how to install and configure it, and several advanced tips to get the most out of this versatile tool.

Table of Contents

  1. What Is Filament PHP?
  2. Why a Repeater Component?
  3. Installing Filament and the Repeater
  4. Basic Usage
  5. Customizing Your Repeater
    • Labels & Help Text
    • Validation Rules
    • Nested Repeaters
  6. Advanced Features
    • Collapsible Groups
    • Drag-and-Drop Sorting
    • Integrating with Relationships
  7. Styling & Layout Considerations
  8. Common Pitfalls & Best Practices
  9. Conclusion

What Is Filament PHP?

Filament PHP is an elegant, modern toolkit for rapidly building administration panels in Laravel applications. It offers ready-made form components, tables, resources, and pages—so you can spend less time scaffolding boilerplate and more time crafting valuable features. Filament’s clean API and fully TailwindCSS-powered UI make it a joy to use for developers and users alike.

Why a Repeater Component?

In many admin scenarios, you need to allow users to input a variable number of similar data entries. Traditional forms force you to define a fixed set of fields, leading to awkward “add more” buttons that require page reloads or custom JavaScript. Filament’s Repeater solves this elegantly:

  • Dynamic Field Groups: Users can add or remove grouped fields on the fly.
  • Seamless Integration: Works out of the box with Filament Forms; no extra JavaScript setup.
  • Data Binding: Automatically serializes repeater data as arrays on your Eloquent models.
  • Customization: Configure labels, limits, validation, and even nested repeaters.

Installing Filament and the Repeater

If you haven’t already, install Filament via Composer:

composer require filament/filament
php artisan filament:install

Filament Forms, including the Repeater component, are bundled in the core package. There’s no separate plugin to install—just import the Repeater class where you need it.

Basic Usage

Let’s say you have a Product model, and each product can have multiple Variants (e.g., color + size combinations). Here’s a simple Filament Resource form using a Repeater:

use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Repeater;
use Filament\Resources\Form;

public static function form(Form $form): Form
{
    return $form
        ->schema([
            TextInput::make('name')
                ->required()
                ->label('Product Name'),

            Repeater::make('variants')
                ->label('Product Variants')
                ->schema([
                    TextInput::make('color')->required(),
                    TextInput::make('size')->required(),
                    TextInput::make('sku')->required(),
                ])
                ->createItemButtonLabel('Add Variant'),
        ]);
}
  • Repeater::make('variants'): Binds to the variants attribute on the model (ideally cast as an array in your Eloquent model).
  • schema([...]): Defines the fields for each repeater item.
  • createItemButtonLabel(...): Customizes the “Add” button text.

Behind the scenes, Filament serializes the repeating groups into an array and stores them in a JSON column:

class Product extends Model
{
    protected $casts = [
        'variants' => 'array',
    ];
}

Customizing Your Repeater

Labels & Help Text

You can personalize labels and help texts to guide users:

Repeater::make('variants')
    ->label('Product Variants')
    ->helpMessage('Add one or more variants for this product')
    ->schema([
        TextInput::make('color')
            ->label('Color Name')
            ->placeholder('e.g. Red'),
        TextInput::make('size')
            ->label('Size')
            ->placeholder('e.g. M, L, XL'),
    ]);

Validation Rules

Integrate Laravel’s validation directly:

Repeater::make('variants')
    ->schema([
        TextInput::make('color')->required()->maxLength(50),
        TextInput::make('size')->required()->maxLength(5),
    ])
    ->minItems(1)
    ->maxItems(10)
    ->validationAttribute('variants');
  • minItems: Ensure at least one entry.
  • maxItems: Cap the number of repeater entries.
  • validationAttribute: Customize error messages.

Nested Repeaters

Repeaters can nest within one another. Imagine each variant can have multiple Images:

Repeater::make('variants')
    ->schema([
        TextInput::make('color')->required(),
        Repeater::make('images')
            ->label('Variant Images')
            ->schema([
                FileUpload::make('image_path')->image()->required(),
                TextInput::make('alt_text')->label('Alt Text'),
            ])
            ->createItemButtonLabel('Add Image'),
    ]);

Keep an eye on model casting—nested arrays become deeply nested JSON.

Advanced Features

Collapsible Groups

For long repeaters, you can collapse items for a cleaner UI:

Repeater::make('specifications')
    ->collapsible()
    ->schema([
        TextInput::make('key')->required(),
        TextInput::make('value')->required(),
    ]);

By default, collapsed items show their index; you can define a summary:

Repeater::make('specs')
    ->collapsible()
    ->summarizeWith(fn(array $state): string => $state['key'] ?? 'New Spec')
    ->schema([/*…*/]);

Drag-and-Drop Sorting

Allow users to reorder items:

Repeater::make('steps')
    ->orderable()
    ->schema([
        TextInput::make('description')->required(),
    ]);

This adds drag handles to reorder steps before saving.

Integrating with Relationships

If you’d rather store repeater data in a related table, Filament can map to HasMany relationships too. For example, a Recipe with many Ingredients:

Repeater::make('ingredients')
    ->relationship()          // auto-detects hasMany('ingredients')
    ->schema([
        TextInput::make('name')->required(),
        TextInput::make('quantity')->required(),
    ]);

Behind the scenes, Filament will call $recipe->ingredients()->createMany($data) on save, keeping your schema normalized.

Styling & Layout Considerations

Because Filament is TailwindCSS-first, you can easily adjust spacing and layout:

  • Grid Layouts: Wrap fields in Grid::make() to align multiple inputs per row.
  • Custom Classes: Use ->columnSpan() or ->extraAttributes(['class' => 'bg-gray-50']) to tweak spacing.
  • Responsiveness: Ensure your repeater fields flow well on mobile by setting sensible column spans.

Example:

Repeater::make('modules')
    ->schema([
        Grid::make(2)
            ->schema([
                TextInput::make('title')->columnSpan(1),
                TextInput::make('duration')->columnSpan(1),
            ]),
    ]);

Common Pitfalls & Best Practices

  1. Model Casting: Always cast repeater-backed attributes to array or json in your model to prevent unexpected string storage.
  2. Data Validation: Use minItems and maxItems to avoid overwhelming users with unlimited inputs.
  3. UX Clarity: Label the “Add” button clearly (e.g., “Add Variant” vs. generic “Add Item”).
  4. Performance: Nested repeaters can bloat your JSON payload. Keep nesting shallow or switch to relationships when data grows large.
  5. Database Migrations: Ensure JSON columns default to [] to avoid null issues:
  6. $table->json('variants')->default(json_encode([]));
  7. Versioning: Filament evolves rapidly. Lock in your composer version and review changelogs for breaking changes to form components.

Conclusion

Filament PHP’s Repeater component transforms the way you build flexible, dynamic forms in Laravel. With just a few lines of code, you offer users the power to manage collections of data—complete with validation, ordering, and customization. Whether you’re crafting a product catalog, building nested surveys, or any scenario calling for repeatable inputs, the Repeater has you covered. Embrace the simplicity and power of Filament, and spend less time stitching together custom JavaScript and more time delivering delightful admin experiences.

#Filament PHP #repeater component #Laravel forms #dynamic form fields #JSON casting #nested repeaters #drag-and-drop sorting

Subscribe to our newsletter

12k+

Subscribers

Weekly

Frequency

Free

Always