Form Class
Defining Forms
A form class lists its fields, decides how their copy renders, and is created through Laravel's service container.
Defining Fields
Every form class must extend Form and implement the fields method, which returns an array of Field instances:
use InertiaUI\Forms\Fields\Submit;
use InertiaUI\Forms\Fields\Textarea;
use InertiaUI\Forms\Fields\TextInput;
use InertiaUI\Forms\Form;
class FeedbackForm extends Form
{
public function fields(): array
{
return [
TextInput::make('name')->required(),
TextInput::make('email')
->email()
->required(),
Textarea::make('message')
->rows(5)
->required(),
Submit::make('Send Feedback'),
];
}
}The package generates each label from the field name, so first_name becomes "First Name" and email stays "Email". You may always set a custom label with the label method:
TextInput::make('email')->label('Your Email Address');Text and HTML Rendering
Form copy is escaped by default. A string passed to label(), help(), a Fieldset legend, or a Fieldset description is displayed as plain text. This keeps application and translated copy safe without any extra work.
Pass an Htmlable value only when the copy intentionally contains trusted inline markup. For example, help text may link to supporting documentation:
use Illuminate\Support\HtmlString;
use InertiaUI\Forms\Fields\Fieldset;
use InertiaUI\Forms\Fields\TextInput;
Fieldset::make([
TextInput::make('vat_number')
->label(new HtmlString('<abbr title="Value Added Tax">VAT</abbr> number'))
->help(new HtmlString('Find this number on your <a href="/billing">billing profile</a>.')),
])
->legend(new HtmlString('Billing <strong>details</strong>'))
->description(new HtmlString('Used for invoices issued by <em>your company</em>.'));Plain strings remain escaped, even when they contain HTML tags. Placeholders always remain plain text, because they're rendered as HTML attributes.
The package derives readable plain text from each Htmlable value for validation messages, accessibility, and other text-only contexts.
Submit labels follow the same rule, so Submit::make(new HtmlString('Save <strong>changes</strong>')) renders the trusted markup together with a plain-text fallback.
Htmlablevalues are rendered as trusted HTML and are not sanitized. Never create anHtmlStringfrom untrusted or user-submitted content.
To let users edit and submit HTML, use the RichText field. Larger application-owned content usually belongs outside the field, in a custom wrapper or slot.
Creating Instances
Use the static make method to create a form instance:
$form = FeedbackForm::make();The make method resolves the form through Laravel's service container, so you may type-hint dependencies in the constructor.
Action URL and Method
The action URL and the HTTP method decide where and how the form submits.
Route Name
You may set the action to a named route with the $actionRoute property:
use InertiaUI\Forms\Form;
class CreateUserForm extends Form
{
protected ?string $actionRoute = 'users.store';
}Or set it fluently with the route method, which also accepts route parameters:
// $user is the User model being edited
$form = EditUserForm::make()->route('users.update', ['user' => $user]);Raw URL
To submit to a raw URL instead of a route name, use the url method:
$form = MyForm::make()->url('/api/submit');HTTP Method
The form defaults to POST. A named route detects the method from the route definition, and that method takes precedence over an explicitly configured one. Set the method explicitly when you use url() or when the form has no named action route:
$form = MyForm::make()->put();The post, get, put, patch, and delete shorthand methods are all available. You may also pass the method name to the method method:
$form = MyForm::make()->method('PUT');Form Behavior
These options change how the rendered form behaves in the browser. Both are off by default.
Unsaved Changes Warning
Forms default to protected bool $unsavedWarning = false. To warn before the user leaves with unsaved changes on every instance, set the property on the class:
use InertiaUI\Forms\Fields\Submit;
use InertiaUI\Forms\Fields\Textarea;
use InertiaUI\Forms\Fields\TextInput;
use InertiaUI\Forms\Form;
class EditPostForm extends Form
{
protected bool $unsavedWarning = true;
public function fields(): array
{
return [
TextInput::make('title')->required(),
Textarea::make('body'),
Submit::make('Save'),
];
}
}To enable the warning for a single instance, call the unsavedWarning method:
$form = EditPostForm::make()->unsavedWarning();The browser's beforeunload confirmation appears once the user tries to close, reload, or leave the current document with unsaved changes. A successful submission resets the dirty baseline.
Validation Error Scrolling
Forms keep the current scroll position after validation errors by default. For long forms that submit from a sticky or top action area, you may enable first-error scrolling:
$form = CheckoutForm::make()->scrollToFirstError();The frontend scrolls only after a failed submission, and only while the first rendered validation error is outside the viewport. It doesn't move focus, so keyboard and assistive-technology context stay with the user's current control. Pass false to disable the behavior for one instance.
Generated PHP forms serialize the same setting. Manual component usage may override it on the frontend:
<Form :form="form" :scroll-to-first-error="true" /><Form form={form} scrollToFirstError />Data and Serialization
A form exposes its current data and serializes to the array your frontend receives.
Getting Form Data
The data method returns the current form data as a key-value array. For a new form, this is the default values. For a bound model, it includes the model's attribute values:
$form = CreateUserForm::make();
$form->data();
// ['name' => null, 'email' => null]
// $user is the User model being edited
$form = EditUserForm::make()->bind($user);
$form->data();
// ['name' => 'Jane Example', 'email' => 'jane@example.com']See Model Binding for how bind() resolves initial values.
Serialization
The toArray method serializes the entire form to the array that Inertia passes to your frontend:
$form = CreateUserForm::make();
$form->toArray();A serialized form includes these top-level keys. Top-level and fieldset keys with a null value are left out. The TextInput entry is shortened, because each field type adds its own keys:
{
"action": "https://example.com/users",
"method": "POST",
"fieldsets": [
{
"columns": 1,
"fields": [
{
"component": "TextInput",
"name": "name",
"label": "Name",
"inputType": "text",
"required": true,
"precognitive": false,
"disabled": false
}
]
}
],
"data": {
"name": null,
"email": null
},
"unsavedWarning": false,
"scrollToFirstError": false
}The frontend Form component reads this structure and renders the form automatically.
The wizard key is left out for normal forms. It holds the serialized wizard settings instead once the form's wizard method returns a WizardConfig or an array. See Wizard for the configuration API.
Data Attributes and Meta
Data attributes and meta both attach extra values to the serialized form. Only data attributes end up in the HTML.
Data Attributes
To add HTML data-* attributes to the form element, use the dataAttribute method:
$form = MyForm::make()
->dataAttribute('testId', 'create-user-form')
->dataAttribute('turbo', 'false');The package converts each key to kebab-case with a data- prefix, so testId becomes data-test-id.
You may also set several attributes at once with the dataAttributes method:
$form = MyForm::make()->dataAttributes([
'testId' => 'create-user-form',
'module' => 'users',
]);Meta
To give frontend code application-specific context from the serialized form config, attach arbitrary metadata with the meta method:
$form = MyForm::make()->meta([
'help_url' => 'https://docs.example.com/forms',
'version' => 2,
]);Unlike data attributes, meta values are not rendered as HTML attributes. They stay in the serialized form config for frontend code to read.
Each meta() call replaces the previously assigned application meta array. Some fields also contribute generated option data under meta.options, and the package merges that generated data into an existing meta.options array during serialization. The options key is reserved, and its value must be an array.
Extending Forms
Forms and fields use Laravel's Macroable, Conditionable, and Tappable traits, so the familiar macro, when, unless, and tap methods work on both.
Extending with Macros
Both Form and Field use Laravel's Macroable trait, so you may add your own methods:
use InertiaUI\Forms\Form;
Form::macro('forCurrentTeam', function () {
return $this->meta([
'team_id' => auth()->user()->current_team_id,
]);
});
// Usage
$form = CreateProjectForm::make()->forCurrentTeam();A field macro works the same way:
use InertiaUI\Forms\Fields\TextInput;
TextInput::macro('phoneNumber', function () {
return $this->tel()->mask('(999) 999-9999');
});
// Usage
TextInput::make('phone')->phoneNumber();Conditional Chaining
All forms and fields support Laravel's Conditionable trait through the when and unless methods:
use App\Models\Business;
use InertiaUI\Forms\Fields\TextInput;
use InertiaUI\Forms\Fields\Toggle;
use InertiaUI\Forms\Form;
class CustomerForm extends Form
{
public function fields(): array
{
return [
TextInput::make('name')->required(),
TextInput::make('company')
->when($this->model instanceof Business, fn ($field) => $field->required()),
Toggle::make('is_admin')
->unless(auth()->user()->isAdmin(), fn ($field) => $field->disabled()),
];
}
}The when and unless methods run while PHP builds the form schema. Use them to conditionally call fluent methods such as required() or disabled().
For conditions based on current form data, use visibleWhen() and hiddenWhen(). For permissions, use authorizedWhen() and authorizedUnless(), so unauthorized fields are not serialized, included in data, or validated.
Tapping
Use tap() when a form or field needs setup from a helper, but you still want to keep chaining:
// Inside the fields method of a form class that defines configureBillingEmail
TextInput::make('billing_email')
->email()
->tap(fn (TextInput $field) => $this->configureBillingEmail($field))
->required();