Content Index
- 1. What is Laravel Inertia and why does it make form handling easier?
- How Vue and Laravel integrate into the same flow
- Real advantages when creating dynamic forms
- 2. Preparing the controller in Laravel to handle forms
- create() method and sending data to the component
- store() method to save records with Inertia
- 3. Creating a basic form in Inertia with Vue
- Sending data using useForm
- State management: processing, errors, and wasSuccessful
- Editing records based on click event
- 1. Modify the listing to enable edit mode
- 2. update method on the client (Vue + Inertia)
- What happens here?
- 3. Controller in Laravel
- 4. Define the update route
- Router Methods
- Router Configuration Options
- Browser History
- Component State
- Preserve Scroll Position
- Custom Headers
- FormData for Files
- The
- Slot Props
- Form Context
- Event Callbacks
- Changes in Inertia v3
- useHttp Hook (Inertia v3)
- Optimistic Updates in Inertia.js 3
- 1. The Traditional Approach (Pessimistic)
- Implementation with router.optimistic
- Usage in Forms with useForm
- The Inertia Component
- Import and Structure
- 2. Using Slots and Destructuring
- Advantages of recentlySuccessful and processing
- Functionality Test
Forms are the components par excellence used to obtain data from the user, and they are one of the main features we have in Laravel Inertia: we can use them while maintaining the classic Laravel schema on the server side while leveraging Vue with Inertia on the client side.
Working with a form in Laravel Inertia is one of the best ways to combine the solidity of the Laravel backend with the fluidity of Vue on the client.
When I started using Inertia, something that really surprised me was how natural it feels to handle forms: they feel like traditional Laravel forms, but with the advantages of an SPA —without full reloads and without having to build an API from scratch.
In this guide, I show you exactly how to implement a form for both creating and editing records, including:
- Controllers in Laravel
- Data validation
- Props and Inertia
- Handling validation errors
Forms are a fundamental tool for collecting user information. When we talk about the update process, we usually start from a listing where the user chooses which record they want to modify.
Upon selecting an item, the application redirects them to the edit form, which already includes the record's identifier. That identifier normally travels in the URL and allows the backend to know which data should be loaded from the database.
Just like in any HTML form, we can include any type of field: input, select, textarea, file inputs, etc.
The key difference with Inertia is that everything flows like an SPA —without full reloads— while maintaining the simplicity of the typical Laravel lifecycle.
Once the user has edited the data, they can submit the form by clicking an "Update" or "Send" button so that Laravel handles validations and subsequent saving to the database, or displays validation errors if something is incorrect.
Laravel Inertia is nothing more than a scaffolding or skeleton for Laravel that adds features to a project to be able to integrate Vue as the client technology, keeping Laravel as the server technology.
1. What is Laravel Inertia and why does it make form handling easier?
Inertia is a bridge that eliminates the typical divorce between backend and frontend. Technically it is not a framework, but a scaffolding that allows using Vue, React, or Svelte as views, while Laravel continues controlling routes, controllers, and validation.
How Vue and Laravel integrate into the same flow
In my case, I describe Inertia as "Vue on steroids", because I can keep using my Laravel controllers as is, but instead of returning a view(), I return an inertia(), which renders a Vue component with the data already included.
Real advantages when creating dynamic forms
- You can use
v-modellike in any Vue app. - You can submit forms with
router.post,router.put, orrouter.deletewithout reloading the page. - Laravel continues handling validation with
FormRequest. - The form state (errors, processing, etc.) is automatically managed by the
useFormhelper.
Inertia greatly facilitates the process of handling forms with Vue, since we don't need to implement a separate REST API; the useForm object simplifies the validation process and form state management.
2. Preparing the controller in Laravel to handle forms
In Laravel, inside a controller working with categories, we create the necessary methods to present the component in Vue via the inertia() function, instead of the classic view() function, which renders a Vue component with the data already available.
app/Http/Controllers/Dashboard/CategoryController.php
create() method and sending data to the component
The create() method is solely responsible for rendering the creation form Vue component. If you need to pass data to the component —for example, a list of parent categories—, you add them as a second argument of inertia():
<?php
namespace App\Http\Controllers\Dashboard;
use App\Http\Controllers\Controller;
use App\Models\Category;
use Illuminate\Http\Request;
class CategoryController extends Controller
{
public function create()
{
return inertia("Dashboard/Category/Create");
}
}store() method to save records with Inertia
The store() method receives the data sent from the Vue form. In my projects, I usually process it like this:
class CategoryController extends Controller
{
public function store(Request $request)
{
Category::create(
[
'title' => request('title'),
'slug' => request('slug'),
]
);
dd($request->all());
}
}Note: dd($request->all()) is only for debugging during development. In production, you should return a redirect() or an inertia() response as appropriate.
3. Creating a basic form in Inertia with Vue
We create the form with its respective v-model directives and handle the submit event to send the data to the previous controller method:
resources/js/Pages/Dashboard/Category/Create.vue
<template>
<form @submit.prevent="submit">
<label for="">Title</label>
<input type="text" v-model="form.title" />
<label for="">Slug</label>
<input type="text" v-model="form.slug" />
<button type="submit">Send</button>
</form>
</template>For the script section, we use the useForm() function, a helper that facilitates error handling and form state in general. When doing the dd() on the server, you will see that along with the form data, internal Inertia properties also arrive:
array:10 [
"title" => "Test"
"slug" => "test-slug"
"isDirty" => true
"errors" => []
"hasErrors" => false
"processing" => false
"progress" => null
"wasSuccessful" => false
"recentlySuccessful" => false
"__rememberable" => true
]Sending data using useForm
Finally, we use the get, post, put, patch, or delete methods available in Inertia's form object to send the form to the server. We can also use the router object directly:
<script>
import { router } from '@inertiajs/vue3'
import { useForm } from "@inertiajs/vue3";
export default {
setup() {
const form = useForm({
title: null,
slug: null,
});
function submit() {
router.post(route("category.store"), form);
}
return { form, submit };
},
};
</script>Note: in recent versions of Inertia v2 and v3, the useForm import is done directly from '@inertiajs/vue3', not from '@inertiajs/inertia-vue3' (legacy package).
State management: processing, errors, and wasSuccessful
The useForm helper automatically exposes the following reactive properties:
form.processing
form.errors
form.wasSuccessfulThese properties synchronize without you having to manage any state manually. For example, you can use form.processing to disable the submit button while the request is in progress, and form.errors to display Laravel's validation messages directly in the template.
Editing records based on click event
Editing an item directly in the listing —without using modals or additional screens— offers a very fluid experience for the user and is extremely simple to implement with Vue and Inertia.
The idea is that when the user clicks on a to-do's name, that <span> is replaced by an <input> to allow inline editing. Upon pressing Enter, the update is sent to the server using Inertia.
Below I explain step by step how to implement it.
1. Modify the listing to enable edit mode
File: resources/js/Pages/Todo/Index.vue
<li v-for="t in todos" class="border py-3 px-4 mt-2" :key="t">
<span v-show="!t.editMode" @click="t.editMode = true">
{{ t.name }}
</span>
<TextInput
v-show="t.editMode"
v-model="t.name"
@keyup.enter="update(t)"
/>
<button @click="remove" class="float-right">
***
</button>
</li>Explanation
We add an additional property called editMode to each to-do, which does not exist in the database model, but is added dynamically on the client side.
editMode === true→ The<input>for editing is shown.editMode === false→ The<span>with the to-do name is shown.
Thanks to Vue's reactivity, changing editMode or name is automatically reflected in the interface without needing extra code.
Behavior
When the user clicks on the <span>, edit mode is activated.
When they press Enter inside the <input>, the update(t) method is executed.
2. update method on the client (Vue + Inertia)
update(todo) {
todo.editMode = false;
router.put(route("todo.update", todo.id), {
name: todo.name,
});
},What happens here?
- Edit mode is deactivated (
editMode = false). - A
PUTrequest is sent to the backend using Inertia'srouter.put. - Only the new name of the to-do is sent.
- This allows a fluid experience without full page reloads.
3. Controller in Laravel
File: app/Http/Controllers/TodoController.php
public function update(Todo $todo, Request $request)
{
$request->validate([
'name' => 'required|string|max:255'
]);
Todo::where("id", $todo->id)
->where('user_id', auth()->id())
->update([
'name' => $request->name,
]);
return back();
}Important points:
- The
namefield is validated with Laravel rules. - It is guaranteed that only the user who owns the to-do can edit it via
where('user_id', auth()->id()). - Only the
namefield is updated.
4. Define the update route
File: routes/web.php
Route::group([
'prefix' => 'todo',
'middleware' => ['auth:sanctum', config('jetstream.auth_session'), 'verified']
], function () {
Route::get('/', [TodoController::class, 'index'])->name('todo.index');
Route::post('store', [TodoController::class, 'store'])->name('todo.store');
Route::put('update/{todo}', [TodoController::class, 'update'])->name('todo.update');
});Router Methods
You can also use the router directly for more precise control over requests:
import { router } from '@inertiajs/vue3'
router.get(url, data, options)
router.post(url, data, options)
router.put(url, data, options)
router.patch(url, data, options)
router.delete(url, options)Router Configuration Options
Browser History
By default, Inertia adds a new entry to the browser history. You can use the replace option to replace the current entry instead of creating a new one:
router.get('/post', data, { replace: true })Component State
By default, visits to the same page force a new instance of the component, which clears any local state: form data, scroll position, and focus states.
In certain situations, it is necessary to preserve the component's state. For example, when submitting a form with validation errors, we need the data entered by the user not to disappear.
To preserve component state between visits to the same page, use the preserveState option:
router.get('/post', data, { preserveState: true })Preserve Scroll Position
When navigating between pages, Inertia mimics default browser behavior and automatically resets the scroll position to the top of the document. To avoid this, use the preserveScroll option:
Inertia resets scroll automatically upon navigation; use
preserveScroll: trueto prevent it.
router.put('/update', data, { preserveScroll: true })Custom Headers
The headers option allows you to add custom HTTP headers to any Inertia request:
router.post('/post', data, {
headers: {
'Custom-Header': 'value',
},
})FormData for Files
When you need to send files, you must tell Inertia to use FormData instead of the default JSON format. To do this, use the forceFormData option:
router.post('/upload', {
image: file,
}, {
forceFormData: true,
})The <Form> Component of Inertia v3
Inertia v3 introduces the <Form> component, which automatically handles form state, validation errors, and processing states, eliminating much of the manual boilerplate.
<template>
<Form
action="/users"
method="post"
#default="{
errors,
hasErrors,
processing,
progress,
wasSuccessful,
recentlySuccessful,
setError,
clearErrors,
resetAndClearErrors,
defaults,
isDirty,
reset,
submit,
}"
>
<input type="text" name="name" />
<div v-if="errors.name">{{ errors.name }}</div>
<button type="submit" :disabled="processing">
{{ processing ? 'Saving...' : 'Save' }}
</button>
<span v-if="recentlySuccessful">Saved successfully!</span>
</Form>
</template>Slot Props
errors- Object with validation errors (uses dot notation for nested fields)hasErrors- Boolean indicating if errors existprocessing- Active boolean while the request is in progressprogress- File upload progresswasSuccessful- Boolean that activates after a successful responserecentlySuccessful- Boolean that activates briefly after success (ideal for visual feedback)isDirty- Boolean indicating if there are unsaved changesdefaults- Method to update form default valuessetError(field, message)- Manually sets an error on a fieldclearErrors()- Clears all form errorsreset()- Restores values to default statesubmit()- Submits the form programmatically
Form Context
If you need to access form state from child components without passing props, you can use the useFormContext composable:
import { useFormContext } from '@inertiajs/vue3'
const form = useFormContext()
// Available only inside a <Form> component
<div v-if="form">
<span v-if="form.isDirty">Unsaved changes</span>
<button @click="form.submit()">Send</button>
</div>Event Callbacks
Callbacks execute at different stages of the HTTP request lifecycle. They are very useful for showing loaders, notifications, or clearing state:
router.post('/post', data, {
onBefore: (visit) => {},
onStart: (visit) => {},
onProgress: (progress) => {},
onSuccess: (page) => {},
onError: (errors) => {},
onCancel: () => {},
onFinish: (visit) => {},
})onBefore: runs before the request starts.onProgress: runs while the request is in progress (useful for progress bars).onSuccess: runs when the server returns a successful response.onError: runs when a problem occurs (validation or server errors).
Changes in Inertia v3
In Inertia v3, some global events were renamed for clarity:
invalid→httpExceptionexception→networkErrorcancel()→cancelAll()
useHttp Hook (Inertia v3)
The useHttp hook is a new feature in Inertia v3 that offers a modern way to make navigation-independent HTTP requests — ideal for API calls without Inertia handling the response as a page visit:
import { useHttp } from '@inertiajs/vue3'
const http = useHttp({
name: '',
email: '',
})
// Basic requests
http.get('/api/users')
http.post('/api/users', { name: 'John' })
// With options and callbacks
http.post('/api/users', { name: 'John' }, {
onSuccess: () => console.log('User created'),
})Optimistic Updates in Inertia.js 3
Optimistic updates are an interface design technique that prioritizes perceived speed.
Instead of waiting for the server to confirm that data has been saved, the interface updates instantly assuming the operation will succeed.
1. The Traditional Approach (Pessimistic)
Normally, the flow is as follows: the user clicks, a loading indicator is shown, we wait for the server response (latency, database, email sending) and, finally, we update the interface in the onSuccess callback:
resources/js/pages/todo/Index.vue
// *** Normal updates (pessimistic approach)
const status = (todo: any) => {
// Updates AFTER receiving server response (slower)
router.post(todoStatus(todo.id).url, {
status: todo.status == '1' ? '0' : '1',
},
{
onError: (errors) => {
add('Validation or server error');
},
onSuccess: () => {
// Updates UPON CONFIRMING changes on the server
todo.status = todo.status == '1' ? '0' : '1';
}
},
);
};
If we simulate a delay with a sleep(2) on the server, the experience is frustrating: the user clicks and has to wait two seconds to see the change. This does not feel natural:
app/Http/Controllers/TodoController.php
class TodoController extends Controller
{
***
function status(Todo $todo)
{
sleep(2);
$randomError = rand(1, 10) <= 7;
if ($randomError) {
throw ValidationException::withMessages([
'status' => 'Random error occurred - optimistic update will rollback',
]);
}
Todo::where("id", $todo->id)->where("user_id", auth()->id())->update([
'status' => request('status') == '1'
]);
return redirect(route('todo.index'));
}
} Implementation with router.optimistic
Inertia.js makes optimistic updates easy via the chained optimistic() method. Let's analyze how it works in a To-Do component where we want to change the completion status.
Previously, we changed the state manually before the server response, which could leave the interface in an invalid state if the server failed:
resources/js/pages/todo/Index.vue
const status = (todo: any) => {
// Updates BEFORE receiving response, but DOES NOT rollback if there's an error
todo.status = todo.status == '1' ? '0' : '1';
router.post(todoStatus(todo.id).url, {
status: todo.status,
},With the new optimistic() method, Inertia manages the automatic rollback for us:
resources/js/pages/todo/Index.vue
const status = (todo: any) => {
const newStatus = todo.status == '1' ? '0' : '1';
router
.optimistic((props) => ({
todos: props.todos.map((t) =>
t.id === todo.id ? { ...t, status: newStatus } : t
),
}))
.post(todoStatus(todo.id).url, {
status: newStatus,
}, {
onError: (errors) => {
add('Validation or logic error', 'error');
},
onFinish: () => {
// Revert loaders if any
}
});
};Here, the block:
.optimistic((props) => ({
todos: props.todos.map((t) =>
t.id === todo.id ? { ...t, status: newStatus } : t
),
}))Applies the change to the UI immediately, assuming there will be no errors on the server. But, just like with migrations in Laravel, Inertia knows exactly what it needs to rollback if an error occurs. The analogy is perfect: the optimistic() method defines the up() of the change, and if it fails, Inertia executes the down() automatically:
return new class extends Migration
{
public function up(): void
{
Schema::create('posts', function (Blueprint $table) {
***
});
}
public function down(): void
{
Schema::dropIfExists('posts');
}
};How does the "magic" work?
- User click: What is inside
optimistic()executes immediately. The interface changes instantly (the icon changes state). - Background request: The server processes the update while the user already sees the expected result.
- Error handling (Rollback): If the server returns an error (for example, a
422or a500), Inertia automatically performs a rollback. You don't need to manually program the "go back" logic; the state returns to its original value based on server data:// Direct server error abort(422, 'Random error occurred - optimistic update will rollback'); // Server error with JSON return response()->json([ 'message' => 'Random error occurred - optimistic update will rollback' ], 422); // Laravel validation error throw ValidationException::withMessages([ 'status' => 'Random error occurred - optimistic update will rollback', ]);
Usage in Forms with useForm
This technique is not limited to the router. You can also use it with the useForm hook. It is very useful, for example, on a "Like" button:
- Action: The user gives a "Like".
- Optimism: We visually increment the counter by +1 immediately.
- Error: If the network or server fails, the counter automatically returns to its previous number.
<Form
action="/todos"
method="post"
:optimistic="(props, data) => ({
todos: [...props.todos, { id: Date.now(), name: data.name, done: false }],
})"
>It is very similar to database migrations: just as we have an up() method to create and a down() method to rollback, the optimistic update assumes the up() and automatically executes the down() (rollback) if something goes wrong.
Using optimistic() saves us from performing manual checks and makes our application feel incredibly fast. Remember that this technique is ideal for lightweight and frequent operations where the probability of success is high (state changes, likes, toggles).
The Inertia <Form> Component
Let's now look at the advanced form component that appears in the official documentation and in the default components that the project brings, such as Edit.vue.
We implement it so you can see how it simplifies all form state management.
Import and Structure
The first thing is to import the component directly from the Inertia package. This component acts as an intelligent wrapper that manages the form state internally:
<Form :action="store()" class="space-y-6">
***
</Form>
import { Head, useForm, Form } from '@inertiajs/vue3'2. Using Slots and Destructuring
Unlike the manual method, here we take advantage of the default slot to directly obtain the variables we need: errors, processing, and recentlySuccessful (among others). The official documentation and Inertia's example components are an excellent reference.
Notice that it is no longer necessary to declare errors as a Prop, since the <Form> component provides it to us automatically through the form context. Modern syntax uses the #default hash to access this data, or you can also use the v-slot directive:
<Form :action="store()" class="space-y-6"
v-slot="{ errors, processing, recentlySuccessful }"
>
***
<div class="flex items-center gap-4">
<Button type="submit" :disabled="processing">
Save
</Button>
<Transition enter-active-class="transition ease-in-out" enter-from-class="opacity-0"
leave-active-class="transition ease-in-out" leave-to-class="opacity-0">
<p v-show="recentlySuccessful" class="text-sm text-neutral-600">
Saved.
</p>
</Transition>
</div>
</Form>Advantages of recentlySuccessful and processing
This is the most powerful part of the modern pattern:
processing: Automatically becomestruewhile the request travels to the server, allowing us to disable the submit button with:disabled="processing"without extra logic.recentlySuccessful: It is a boolean that activates right after a successful response and automatically deactivates after a few seconds. It is perfect for showing that small "Saved" text with a smooth transition, without needing to manage timers manually.
Functionality Test
If we submit the form with errors, you will see that the request arrives correctly and Laravel's validation messages appear where they should. When creating a category correctly (for example, "Category 2"), the success message will appear and disappear automatically thanks to the animation that you can customize to your liking with Vue's Transition.
We have gone from a manual form to a fully automated one. We no longer declare error props or manage timers for success messages; Inertia's <Form> component and its helpers do all the heavy lifting.
The next step is for you to learn how to implement file uploads with Drag and Drop in Laravel Inertia.