How to Effectively Reuse Laravel Filament Forms

lokman musliu
Lokman Musliu

June 3, 2024 · 3 min read · 1,031 views

Filament Logo

Laravel Filament is a popular admin panel for Laravel applications known for its simplicity and flexibility. One of its many features is the ability to create forms quickly and efficiently. However, as your application grows, you might need to reuse forms in multiple places. Luckily, Laravel Filament forms are designed with reusability in mind. This blog post will explore some best practices for reusing Laravel Filament forms, ensuring your codebase remains DRY (Don't Repeat Yourself) and maintainable.

Create a Form Component

The first step in reusing a form is to create a separate form component. This is a PHP class that defines the form's fields, validation rules, and any custom behavior. By encapsulating this logic in a single place, you can easily include it in different parts of your application.

Step 1: Define the Form Component

Create a new PHP class for your form component. For example, if you're creating a form for managing users, you might create a UserForm.php file in your app/Filament/Components directory:

<?php

namespace App\Filament\Components;

use Filament\Forms\Components\{Select, TextInput};

class UserForm
{
    public static function schema(): array
    {
        return [
            TextInput::make('name')
                ->required()
                ->label('Name'),
            TextInput::make('email')
                ->email()
                ->required()
                ->label('Email Address'),
            Select::make('role')
                ->options([
                    'admin' => 'Administrator',
                    'user' => 'User',
                ])
                ->required()
                ->label('Role'),
            // Add more fields as needed...
        ];
    }
}

Step 2: Use the Form Component

Now that you have defined your form component, you can reuse it wherever you need a user form in your application. For instance, you might use the same UserForm on the UserResource and on a custom Action .

Here is how you can call the custom Form component from your UserResource:

<?php

namespace App\Filament\Resources;

use App\Models\User;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use App\Filament\Components\UserForm;
use App\Filament\Resources\UserResource\Pages;

class UserResource extends Resource
{
    protected static ?string $model = User::class;

    protected static ?string $navigationIcon = 'heroicon-o-user';

    public static function form(Form $form): Form
    {
        return $form->schema(
            UserForm::schema(),
        );
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListUser::route('/'),
            'create' => Pages\CreateUser::route('/create'),
            'view' => Pages\ViewUser::route('/{record}'),
            'edit' => Pages\EditUser::route('/{record}/edit'),
        ];
    }
}

By calling UserForm::schema(), you're reusing the same form schema and ensuring consistency across different parts of your application.

Customize the Form for Different Contexts

Sometimes, you may need to slightly alter the form based on the context. For example, you might want to disable certain fields based on passed arguments. You can achieve this by passing arguments to your form component.

Update the Form Component

Modify your form component to accept parameters and use them to conditionally modify the form schema:

<?php

namespace App\Filament\Components;

use Filament\Forms\Components\{Select, TextInput};

class UserForm
{
    public static function schema(array $options = []): array
    {
        return [
            TextInput::make('name')
                ->required()
                ->hidden($options['nameHidden'] ?? false)
                ->label('Name'),
            TextInput::make('email')
                ->email()
                ->required()
                ->label('Email Address'),
            Select::make('role')
                ->options([
                    'admin' => 'Administrator',
                    'user' => 'User',
                ])
                ->required()
                ->label('Role'),
            // Add more fields as needed...
        ];
    }
}

Step 2: Pass Options When Using the Form

When calling your form component, pass the options as needed:

<?php

public static function form(Form $form): Form
{
    return $form->schema(
        UserForm::schema(options: [
            'nameHidden' => true,
        ]),
    );
}

Conclusion

Reusing forms in Laravel Filament not only saves you time but also helps prevent errors and inconsistencies in your application. By extracting your form logic into a separate, reusable component, you can ensure that your forms stay consistent and are easy to maintain. Remember to parameterize your components for additional flexibility, and you'll be well on your way to a cleaner and more efficient codebase.


Bring Your Ideas to Life 🚀

If you need help with a Laravel project let's get in touch.

Lucky Media is proud to be recognized as a Top Laravel Development Agency

lokman musliu
Lokman Musliu

Founder and CEO of Lucky Media

Technologies:

Filament
Laravel
Heading Pattern

Related Posts

Stay up to date

Be updated with all news, products and tips we share!