【Laravel】How to Use Inertia Forms in a Nutshell
Thank you for your continued support.
This article contains advertisements that help fund our operations.
Table Of Contents
A concise guide on using Inertia.js forms in Laravel projects.
Introduction
This article focuses on form implementation, particularly assuming the use of useForm
with Laravel's Inertia.js.
For those who want to implement it step by step, refer to this article on implementing with Inertia.js:
Introducing the Basics of Inertia.js with a Step-by-Step Guide
Basic Usage
Here is the basic implementation when using Inertia.js with React:
import { useForm } from "@inertiajs/react"
export default function Create() {
const form = useForm({
title: "",
content: "",
})
const createPost = e => {
e.preventDefault() // Prevent default form submission
form.post(route("post.store"), {
preserveScroll: true,
onSuccess: () => reset(), // Reset form
onError: errors => {
// Handle errors
},
})
}
return (
<>
<div className="w-4/5 mx-auto py-12">
<h1>Create New Post</h1>
<form onSubmit={createPost}>
<div>
<div>
<input
value={form.data.title}
onChange={e => form.setData("title", e.target.value)}
placeholder="Title"
/>
</div>
<div>
<textarea
value={form.data.content}
onChange={e => form.setData("content", e.target.value)}
placeholder="Content"
></textarea>
</div>
<button>Submit</button>
<div>{form.data.title}</div>
</div>
</form>
</div>
</>
)
}
This is the basic structure.
Below, we summarize the properties and their usage. Though lengthy, these features are worth exploring for potential new insights.
Checking Properties
Using useForm
provides various reactive properties, making it very convenient. Here is a detailed look at the available properties:
- data
- setData
- get
- post
- put
- patch
- delete
- submit
- transform
- cancel
- reset
- clearErrors
- errors
- hasErrors
- setError
- progress
- isDirty
- processing
- recentlySuccessful
- wasSuccessful
- setDefaults
Using Properties
For example, with data
and cancel
:
const form = useForm()
const data = form.data
const cancel = form.cancel
Alternatively:
const { data, cancel } = useForm()
data
Holds the input values for the form. The initial values defined in useForm
are stored here.
const { data } = useForm({
title: "",
content: "",
})
console.log(data.title) // Current title
console.log(data.content) // Current content
<div>{data.title}</div>
setData
Dynamically updates specific fields in the form.
const { setData } = useForm({
title: "",
content: "",
})
setData("title", "New Title")
setData("content", "New Content")
get
Sends a GET request.
const Posts = () => {
form.get(route("post.index"), {
onSuccess: () => {},
onError: errors => {},
})
}
Corresponds to Laravel's GET routing:
Route::get('/posts', [PostController::class, 'index'])->name('post.index');
post
Sends a POST request.
const createPost = () => {
form.post(route("post.store"), {
onSuccess: () => {},
onError: errors => {},
})
}
Corresponds to Laravel's POST routing:
Route::post('/post', [PostController::class, 'store'])->name('post.store');
put
Sends a PUT request.
const updatePost = id => {
form.put(route("post.update", id), {
onSuccess: () => {},
onError: errors => {},
})
}
Corresponds to Laravel's PUT routing:
Route::put('/post/{id}/update', [PostController::class, 'update'])->name('post.update');
patch
Sends a PATCH request.
const updatePostPartially = id => {
form.patch(route("post.update", id), {
onSuccess: () => {},
onError: errors => {},
})
}
Corresponds to Laravel's PATCH routing:
Route::patch('/post/{id}/update', [PostController::class, 'update'])->name('post.update');
delete
Sends a DELETE request.
const deletePost = id => {
form.delete(route("post.destroy", id), {
onSuccess: () => alert("Post deleted successfully!"),
})
}
Corresponds to Laravel's DELETE routing:
Route::delete('/post/{id}/destroy', [PostController::class, 'destroy'])->name('post.destroy');
submit
Allows manually specifying methods such as post
, put
, patch
, or delete
.
const method = "post" // `put`, `patch`, `delete`
const customSubmit = (method, id) => {
form.submit(method, route(`post.store`, id), {
onSuccess: () => {},
onError: errors => {},
})
}
transform
Transforms data before submission.
form.transform(data => ({
...data,
title: data.title.trim(),
}))
cancel
Cancels the current form submission.
const cancelRequest = () => {
form.cancel() // Cancel submission
}
reset
Resets form data to its initial state.
form.reset()
form.reset("title") // Reset specific fields
clearErrors
Clears current form errors.
const handleClearErrors = () => {
form.clearErrors() // Clear errors
}
errors
Holds validation errors from form submissions. Easily display validation errors as follows:
<span>{form.errors.title}</span>
Laravel validation:
public function store(Request $request)
{
$validatedData = $request->validate([
'title' => 'required|string|max:255', // Title is required, a string, max length 255
'content' => 'nullable|string', // Content is optional, a string
]);
// ...
}
hasErrors
Checks if there are errors (true
or false
).
if (form.hasErrors) {
alert("There are errors in the form!")
}
<input
value={form.data.title}
onChange={(e) => form.setData('title', e.target.value)}
placeholder="Title"
required
/>
<button disabled="{form.hasErrors}">Submit</button>
setError
Manually sets errors.
form.setError({
title: "Title is required",
content: "Content cannot be empty",
})
progress
Indicates upload progress (for file uploads).
This is really convenient.
form.post(route("upload"), {
onProgress: progress => {
console.log(`Upload progress: ${progress.percentage}%`)
},
})
{form.progress &&
<progress value="{form.progress.percentage}" max="100"></progress>}
isDirty
Determines whether the form data has been changed.
True if modified.
if (form.isDirty) {
alert("The form has been modified!")
}
<button disabled="{!form.isDirty}">Save Changes</button>
processing
Indicates that the form is being submitted.
True during submission.
if (form.processing) {
console.log("Submitting...")
}
<button disabled="{form.processing}">Submit</button>
recentlySuccessful
True after a successful submission, then reverts to False after a few seconds.
{form.recentlySuccessful &&
<p>Submission was successful!</p>
}
wasSuccessful
Determines whether the most recent request was successful.
if (form.wasSuccessful) {
alert("Submission was successful!")
}
setDefaults
Sets the default values for the form.
form.setDefaults({
title: "Default Title",
content: "Default Content",
})
Conclusion
That's a summary of the useful properties.
console.log(form)
I tried to list all the properties you can check, but if there are more, please let me know!
I hope this helps someone.