Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

valentin_vranic's avatar

Livewire 3 extracted form

I want to extract my filter form to separate Form class. However I have 2-3 selects where the data is coming from the DB. What would be a good approach? Because IDK how to initialize and set the value in the extracted Form class, to that array where the options of the select are supposed to be. Because there is no mount method in Form.

So one of my solutions would be to init those Form properties in the parent component's mount method like:

public function mount(): void
{
    $this->form->trunks = $this->form->getTrunks();
}	

Is this the only one? Thanks in advance

0 likes
3 replies
LaryAI's avatar
Level 58

To extract your filter form into a separate Form class in Livewire 3, you can follow a structured approach to handle the initialization and setting of values, especially for select options that come from the database. Here’s a step-by-step solution:

  1. Create the Form Class: Define a form class that will handle the form data and validation.
namespace App\Http\Livewire\Forms;

use Livewire\Form;

class FilterForm extends Form
{
    public $trunks = [];

    public function getTrunks()
    {
        // Fetch trunks from the database
        return \App\Models\Trunk::all()->pluck('name', 'id')->toArray();
    }
}
  1. Initialize the Form in the Parent Component: In your parent Livewire component, initialize the form and set the select options in the mount method.
namespace App\Http\Livewire;

use Livewire\Component;
use App\Http\Livewire\Forms\FilterForm;

class ParentComponent extends Component
{
    public FilterForm $form;

    public function mount(): void
    {
        $this->form = new FilterForm();
        $this->form->trunks = $this->form->getTrunks();
    }

    public function render()
    {
        return view('livewire.parent-component');
    }
}
  1. Create the Blade View: In your Blade view, bind the form properties to the select inputs.
<!-- resources/views/livewire/parent-component.blade.php -->
<div>
    <form wire:submit.prevent="submit">
        <select wire:model="form.trunks">
            @foreach($form->trunks as $id => $name)
                <option value="{{ $id }}">{{ $name }}</option>
            @endforeach
        </select>
        <!-- Add other form fields as needed -->
        <button type="submit">Submit</button>
    </form>
</div>
  1. Handle Form Submission: Add a method in your parent component to handle form submission.

This approach ensures that your form class is cleanly separated and reusable, while still allowing you to initialize and set values from the parent component. The mount method in the parent component is used to fetch and set the select options from the database.

Please or to participate in this conversation.