From Static to Dynamic: Creating a Powerful Form Builder with Livewire

Learn how to build a dynamic form builder in Laravel Livewire with repeaters, file uploads, and component-based fields. Step-by-step guide with code examples.

Building dynamic forms is a common requirement in modern applications. Instead of hardcoding fields, you might want users to add components (like text inputs, dropdowns, file uploads, or repeaters) that automatically render inside a master form. With Laravel Livewire, you can develop dynamic form builder in a clean and interactive way without writing tons of JavaScript.

Step 1: Create a Livewire Component

Run the artisan command to create your base form builder component with livewire:

php artisan make:livewire FormBuilder

This creates two files:

  • app/Http/Livewire/FormBuilder.php (backend logic)
  • resources/views/livewire/form-builder.blade.php (frontend view)

Step 2: Define Available Components

Inside app/Http/Livewire/FormBuilder.php, let’s define a list of available components. Each component has a name and a JSON configuration of its fields.

public $availableComponents = [
    [
        'name' => 'Text Input',
        'fields' => [
            ['type' => 'text', 'label' => 'Enter Text', 'value' => '']
        ]
    ],
    [
        'name' => 'Email',
        'fields' => [
            ['type' => 'email', 'label' => 'Enter Email', 'value' => '']
        ]
    ],
    [
        'name' => 'File Upload',
        'fields' => [
            ['type' => 'file', 'label' => 'Upload File', 'value' => '']
        ]
    ],
    [
        'name' => 'Repeater',
        'fields' => [
            ['type' => 'repeater', 'label' => 'Repeater Field', 'items' => []]
        ]
    ],
];

We’ll store user-selected components in:

public $formComponents = [];

Step 3: Add Components to the Form

When a user clicks a component, push it to the form array:

public function addComponent($index)
{
    $component = $this->availableComponents[$index];
    $this->formComponents[] = $component;
}

Step 4: Render Dynamic Fields

Render all selected components to form-builder.blade.php:

<div>
    <!-- Component Menu -->
    <h3>Available Components</h3>
    @foreach ($availableComponents as $i => $comp)
        <button wire:click="addComponent({{ $i }})">
            {{ $comp['name'] }}
        </button>
    @endforeach

    <hr>

    <!-- Dynamic Form -->
    <form wire:submit.prevent="save">
        @foreach ($formComponents as $cIndex => $component)
            <div class="component">
                <h4>{{ $component['name'] }}</h4>

                @foreach ($component['fields'] as $fIndex => $field)
                    @if ($field['type'] === 'text')
                        <input type="text"
                               wire:model="formComponents.{{ $cIndex }}.fields.{{ $fIndex }}.value"
                               placeholder="{{ $field['label'] }}">
                    @elseif ($field['type'] === 'email')
                        <input type="email"
                               wire:model="formComponents.{{ $cIndex }}.fields.{{ $fIndex }}.value"
                               placeholder="{{ $field['label'] }}">
                    @elseif ($field['type'] === 'file')
                        <input type="file"
                               wire:model="formComponents.{{ $cIndex }}.fields.{{ $fIndex }}.value">
                    @elseif ($field['type'] === 'repeater')
                        <button type="button"
                                wire:click="addRepeaterItem({{ $cIndex }}, {{ $fIndex }})">
                            ➕ Add Row
                        </button>

                        @foreach ($field['items'] as $rIndex => $item)
                            <input type="text"
                                   wire:model="formComponents.{{ $cIndex }}.fields.{{ $fIndex }}.items.{{ $rIndex }}.value"
                                   placeholder="Repeater Item {{ $rIndex + 1 }}">
                        @endforeach
                    @endif
                @endforeach
            </div>
        @endforeach

        <button type="submit">Save Form</button>
    </form>
</div>

Step 5: Handle Repeaters in Form

If clicked component is repeater, push it to the form array as follows:

public function addRepeaterItem($cIndex, $fIndex)
{
    $this->formComponents[$cIndex]['fields'][$fIndex]['items'][] = ['value' => ''];
}

Step 6: Save the Form Data

Finally, handle form saving:

public function save()
{
    // Just dump the data for now
    dd($this->formComponents);

    // In real apps, store in DB as JSON
}

Conclusion

Dynamic form builders don’t have to be complicated. With Laravel Livewire, you can build fully interactive forms that support repeaters, file uploads, and dynamic components without writing heavy JavaScript.

This approach keeps your codebase clean, your forms flexible, and your users happy. Once you have the basics working, it’s easy to extend the builder with drag-and-drop sorting, conditional fields, or rich text editors.

Whether you’re building an admin panel, a survey tool, or a custom CMS, this Livewire-powered dynamic form structure gives you a strong foundation to adapt to almost any use case.

Building a Dynamic XML Sitemap in Laravel: A Step-by-Step Guide

Learn how to create a dynamic XML sitemap in Laravel from a list of links. Step-by-step guide with controller, Blade template, and route setup for your web app.

If you’ve ever wondered how search engines like Google actually find and index your Laravel-powered website, the answer often lies in a well-structured XML sitemap. Without one, even your best content might stay hidden in the shadows. The good news? Generating a dynamic XML sitemap in Laravel is easier than you think.

In this guide, I’ll walk you through a step-by-step process to build a dynamic XML sitemap in Laravel from any list of links—helping your site become more SEO-friendly and crawlable in just minutes.

Step 1: Create a Controller

We’ll start by creating a SitemapController to generate the XML response.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Response;

class SitemapController extends Controller
{
    public function index()
    {
        // Example list of links (this can come from DB or config)
        $links = [
            ['url' => url('/'), 'updated_at' => now()],
            ['url' => url('/about'), 'updated_at' => now()->subDays(2)],
            ['url' => url('/contact'), 'updated_at' => now()->subDays(5)],
        ];

        $content = view('sitemap', compact('links'));

        return response($content, 200)
            ->header('Content-Type', 'application/xml');
    }
}

You can extend this controller to fetche links from your database (e.g., posts, products, categories) automatically instead of a manual list like below:

<?php

namespace App\Http\Controllers;

use App\Models\Page;
use Illuminate\Http\Response;

class SitemapController extends Controller
{
    public function index()
    {
        // Example list of links (this can come from DB or config)
        $links = Page::all();

        $content = view('sitemap', compact('links'));

        return response($content, 200)
            ->header('Content-Type', 'application/xml');
    }
}

Alternative Solution

If you don’t want to create controller, you can add this code directly to routes/web.php route as follows:

<?php

use App\Models\Page;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Route;

Route::get('/sitemap.xml', function () {
    $links = Page::all();

    $content = view('sitemap', [
        'links' => $links,
    ]);

    return response($content, 200)
            ->header('Content-Type', 'application/xml');
});

Step 2: Create the Blade View

Create a new file at resources/views/sitemap.blade.php and paste the following code:

{!! '<?xml version="1.0" encoding="UTF-8"?>' !!}
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    @foreach ($links as $link)
        <url>
            <loc>{{ $link->url }}</loc>
            <lastmod>{{ \Carbon\Carbon::parse($link->updated_at)->toAtomString() }}</lastmod>
            <changefreq>weekly</changefreq>
            <priority>0.8</priority>
        </url>
    @endforeach
</urlset>

Note: We use {!! '<?xml version="1.0" encoding="UTF-8"?>' !!} because Blade treats <?xml ... ?> as a PHP tag, which causes a syntax error.


Step 3: Add the Route

Open routes/web.php and add:

use App\Http\Controllers\SitemapController;

Route::get('/sitemap.xml', [SitemapController::class, 'index']);

Note: If you have directly added the code of sitemap to this file, then you can skip this step.


Step 4: Test Your Sitemap

Now, visit:

https://yourapp.com/sitemap.xml

You should see a valid sitemap like this:

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc>https://yourapp.com/</loc>
        <lastmod>2025-09-17T09:10:00+00:00</lastmod>
        <changefreq>weekly</changefreq>
        <priority>0.8</priority>
    </url>
    <url>
        <loc>https://yourapp.com/about</loc>
        <lastmod>2025-09-15T09:10:00+00:00</lastmod>
        <changefreq>weekly</changefreq>
        <priority>0.8</priority>
    </url>
</urlset>

Conclusion

With just a few steps, you’ve created a dynamic XML sitemap in Laravel. You can extend this by fetching links from your database (e.g., blog posts, products, categories) instead of a static list.

This setup ensures your site is search engine friendly and keeps your content crawlable and indexable.

Filament Table Actions: Pro Tips Every Developer Should Know

Discover advanced tips to customize Filament table actions in Laravel. Learn how to auto-mutate data, load custom views in modals, and create state-toggling actions with confirmation and notifications.

Filament resource table actions offer powerful customization for crafting seamless admin experiences. Let’s explore some high-impact tricks every Laravel developer should know:

Trick 1: Automatically Mutate Form Data in the Edit Action

Need to auto-update a field every time you edit from the table? You can do this with the mutateFormDataUsing() method in your EditAction:

use Filament\Tables;
use Filament\Tables\Table;

public static function table(Table $table): Table
{
    return $table
        ->columns([
            // Your columns...
        ])
        ->actions([
            Tables\Actions\EditAction::make()
                ->mutateFormDataUsing(function (array $data): array {
                    $data['status'] = 'updated'; // auto-set status before save
                    return $data;
                }),
        ]);
}

This ensures the status field is automatically set to "updated" whenever an edit occurs.

Trick 2: Customize an Action to Load a View in a Modal

Standard actions don’t always cut it. For instance, you might want to display a list of users who liked a blog post in a modal. Here’s a clean way to do it:

Action::make('showLikes')
    ->label('Likes')
    ->icon('heroicon-o-heart')
    ->visible(fn($record) => $record->likes()->count() > 0)
    ->modalHeading('Likes')
    ->modalContent(function ($record) {
        return view('filament.components.likes-list', [
            'blogId' => $record->id,
        ]);
    })
    ->modalSubmitAction(false)
    ->modalCancelAction(false)
    ->modalWidth('lg'),

This opens a modal showing your custom view, without extra buttons.

Trick 3: Add a State-Toggling Action with Confirmation and Notification

Want a sleek toggle for boolean flags like activation status, complete with confirmation and feedback? Try this:

Tables\Actions\Action::make('toggleActive')
    ->label(fn($record) => $record->is_active ? 'Deactivate' : 'Activate')
    ->icon(fn($record) => $record->is_active ? 'heroicon-o-x-circle' : 'heroicon-o-check-circle')
    ->color(fn($record) => $record->is_active ? 'danger' : 'success')
    ->requiresConfirmation()
    ->action(function ($record) {

        $actionString = $record->is_active ? 'deactivated' : 'activated';

        $record->update([
            'is_active' => !$record->is_active,
        ]);

        Notification::make()
            ->title('Blog has been ' . $actionString . ' successfully')
            ->success()
            ->send();
    }),

This delivers an intuitive toggle experience—confirm first, then notify on change.


Why These Tips Matter

These action enhancements help you:

  • Automate workflows (e.g., setting status instantly in edit forms).
  • Visualize complex data elegantly (e.g., view likes in a modal).
  • Ensure user clarity and feedback with confirmation dialogs and notifications.

This is especially valuable when building advanced admin panels with Filament—turning UI logic into polished user experiences.

Laravel Filament MD5 Password Authentication Guide

Learn how to enable MD5 password authentication in Laravel Filament by creating a custom hasher and updating the AuthServiceProvider for legacy systems.

⚠️ Security Warning:

MD5 is not secure for password hashing and should only be used for compatibility with legacy systems. Consider migrating to bcrypt or argon2 for secure password storage.

If you are working on a Laravel application using Filament Admin and you already have users table with passwords are stored as MD5 hashes, Laravel makes it possible to register a custom hash driver so authentication still works.

In this article, we will learn how to develop custom hash driver for legacy systems, which can use Filament Admin.

Step 1 – Create the MD5 Hasher Class

Laravel’s hash drivers only need three methods: make, check, and needsRehash. We’ll create a simple MD5-based hasher class as follows:

namespace App\Hashing;

class Md5Hasher
{
    public function make($value, array $options = [])
    {
        return md5($value);
    }

    public function check($value, $hashedValue, array $options = [])
    {
        return md5($value) === $hashedValue;
    }

    public function needsRehash($hashedValue, array $options = [])
    {
        return false;
    }
}

In this hasher class, we used md5 function to encrypt the data.

Step 2 – Register the MD5 Driver in AuthServiceProvider

We need to register this hash driver class to the app/Providers/AuthServiceProvider file as follows,

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Hash;
use App\Hashing\Md5Hasher;

class AuthServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $this->app->make('hash')->extend('md5', function() {
            return new Md5Hasher;
        });
    }
}

Step 3 – Set Laravel to Use MD5 by Default

After register to the service provider, we need to change the authentication driver for laravel. You can do it from .env file or config/hashing.php file.

In .env:

HASH_DRIVER=md5

Or in config/hashing.php:

'default' => env('HASH_DRIVER', 'md5'),

Step 4 – Ensure Passwords Are Stored as MD5

When creating or updating users, Laravel will now use MD5 automatically:

use Illuminate\Support\Facades\Hash;
use App\Models\User;

$user = new User();
$user->name = 'Admin';
$user->email = 'admin@example.com';
$user->password = Hash::make('secret'); // stored as MD5
$user->save();

How It Works in Filament

Filament uses Laravel’s built-in authentication (Auth::attempt()), which in turn uses Hash::check(). Because we overrode the hash driver, Filament logins will automatically work with MD5 passwords.

Bonus: Supporting Both MD5 and bcrypt

If you’re migrating from MD5 to bcrypt, you can check both formats:

public function check($value, $hashedValue, array $options = [])
{
    if (md5($value) === $hashedValue) {
        return true; // MD5 match
    }

    return password_verify($value, $hashedValue); // bcrypt/argon
}

This way, old MD5 passwords still work, but you can rehash them to bcrypt on the next login.

Final Thoughts

  • Use MD5 only for compatibility with old systems.
  • If possible, rehash MD5 passwords to bcrypt or argon2 after the first successful login.
  • Filament will automatically use your custom MD5 logic since it relies on Laravel’s authentication system.

How to Insert Repeater Field Entries as Rows to Table in Laravel Filament

Learn how to convert repeater field JSON data into individual table rows in Laravel Filament using a custom button action. A practical guide for syncing structured form data.

When building admin panels using Laravel Filament, the Repeater field is a powerful way to collect dynamic sets of data — such as specifications, tags, or features. Often, these repeater entries are stored as a JSON array in the database. But what if you want to convert those JSON entries into individual rows in another table — for analytics, reporting, or normalization?

In this article, we’ll walk through how to:

  • Collect data using a Repeater field (stored as JSON)
  • Add a button to your Filament admin to insert each entry as a row in another table
  • Do this on-demand, without preloading data from the related table

The Use Case

Let’s assume you’re managing products with technical specifications.

  • You store specifications in a specifications JSON column of the products table using a Filament Repeater.
  • When a button is clicked (e.g., “Insert Repeater Entries”), each specification should be copied into a product_specifications table, with one row per entry.

Step-by-Step Guide

Step 1: Set Up the Repeater Field

Add a specifictions repeater field with multiple fields in product form as follows:

Repeater::make('specifications')
    ->schema([
        TextInput::make('key'),
        TextInput::make('value'),
        TextInput::make('unit'),
        TextInput::make('description'),
        TextInput::make('notes'),
    ])

This will create specifications repeater field in which you can add multiple rows of specifications for any product. This data is stored in the product_pecifications column of your products table as a JSON array.

Step 2: Create the Target Table

Create a migration for new table to hold individual specification entries using this command:

php artisan make:model ProductSpecification -m

It will create 2 files as follows:

  • Model File: app/Models/ProductSpecification.php
  • Migration File: database/migrations/xxxx_xx_xx_xxxxxx_create_product_specifications_table.php

Step 3: Run the Migration File

Update the migration file as per your repeater field entry as follows:

Schema::create('product_specifications', function (Blueprint $table) {
    $table->id();
    $table->foreignId('product_id')->constrained()->onDelete('cascade');
    $table->string('key')->nullable();
    $table->string('value')->nullable();
    $table->string('unit')->nullable();
    $table->text('description')->nullable();
    $table->text('notes')->nullable();
    $table->timestamps();
});

You can now run the migration using migrate command.

php artisan migrate

It will create a product_specifictions table in the database.

Step 4: Add a Button to Trigger the Insert

In your ProductResource\Pages\ViewProduct or EditProduct, add a custom action to generate specifications entries from the repeater field in product form.

use Filament\Actions\Action;

public function getHeaderActions(): array
{
    return [
        Action::make('Insert Repeater Entries')
            ->requiresConfirmation()
            ->action(function () {
                $specs = $this->record->specifications ?? [];

                if (!is_array($specs)) {
                    $specs = json_decode($specs, true) ?? [];
                }

                foreach ($specs as $spec) {
                    \App\Models\ProductSpecification::create([
                        'product_id'  => $this->record->id,
                        'key'         => $spec['key'] ?? null,
                        'value'       => $spec['value'] ?? null,
                        'unit'        => $spec['unit'] ?? null,
                        'description' => $spec['description'] ?? null,
                        'notes'       => $spec['notes'] ?? null,
                    ]);
                }

                $this->notify('success', 'Specifications inserted successfully.');
            }),
    ];
}

You can name the button anything, such as “Sync Specifications” or “Publish to Table”. It will manually extract the JSON data and insert it as rows in the product_specifications table.

Benefits of This Approach

  • Keeps your form simple and user friendly by storing repeater data in JSON.
  • Normalizes data later when needed — perfect for one-time inserts or batch operations.
  • Doesn’t require eager loading or nested relationship editing.

Avoid Duplicate Inserts

You can prevent duplicate imports by checking if rows already exists by adding the following check before adding the specifications in above code:

if ($this->record->productSpecifications()->exists()) {
    $this->notify('warning', 'Specifications already exist.');
    return;
}

Conclusion

Using repeater field gives you flexibility in how you manage structured, dynamic data in Laravel Filament. You can let users manage repeater fields easily, while keeping your database clean and relational by syncing data to separate tables on demand.

Whether for analytics, reporting, or integration, separating repeater entries into rows gives you the best of both worlds: JSON-based forms with relational data power.