Example: React (Inertia) Address Form
Last updated: 2026-11-24
A complete address form in React on the package's HTTP API, for an Inertia app. It shows the country's fields with its labels, cascading subdivision dropdowns, geocodes line 1 when the user leaves it, lets the user choose between their version and the standardized one, and saves through your own controller.
Example code, not a shipped component. Copy it into your app and adapt it. The package doesn't ship React components yet: official React (1.3) and Vue (1.4) components are planned, after a standalone Livewire form in 1.2. See Headless Usage for the other options.
Table of Contents
Requirements
- An Inertia app with React (
@inertiajs/react) and axios, served by the same Laravel app as the package. - The HTTP API enabled, with the default
webmiddleware (or['web', 'auth']for signed-in users only):
ADDRESS_API_ENABLED=true- A Google Maps server key (
GOOGLE_MAPS_SERVER_KEY) for geocoding, and a verification provider if you want addresses verified (Verification).
CSRF needs no code: Laravel sets the XSRF-TOKEN cookie, and axios and Inertia send it back on every POST.
How it works
| Step | Request |
|---|---|
| Load the country list | GET /address-api/countries |
| Pick a country: which fields to show, their labels, which are required | GET /address-api/countries/{code} |
| Fill a dropdown for each subdivision level the country has, once the level above is chosen | GET /address-api/countries/{code}/subdivisions?field=…&parent=… |
| Leave line 1 after typing or pasting an address | POST /address-api/resolve/input |
| Click Verify | POST /address-api/verify |
| Save | POST /addresses (your route) |
resolve/input and verify both return a ResolvedAddress record with status 200, even when nothing was found:
success: false: nothing resolved;error.codesays why. The example says nothing forincomplete_queryandzero_results(the user is still typing, as in the Filament form) and shows the message for the rest (an outage, a rejected API key).requires_choice: true: the provider verified a standardized version that differs from what the user entered. The example showsoriginalnext tofields, highlights the field names inchanges, and lets the user pick.- Otherwise
fieldsis the complete record: the fields, subdivision IDs, coordinates and the verification state. When the provider rejected the address,fieldsis the address as entered, flaggedneeds_review, andverification_errorsays why.
Before calling resolve/input, the example checks that line 1 changed and has at least 5 characters and a digit. The package's BlurGeocodingPolicy isn't available over HTTP; resolve/input returns incomplete_query without calling Google when the address can't succeed yet.
The component
resources/js/Components/AddressForm.jsx:
import { useEffect, useState } from 'react';
import axios from 'axios';
import { router } from '@inertiajs/react';
const API = '/address-api';
// Subdivision fields, top-down, each with the ID field of the level above
const LEVELS = [
{ field: 'administrative_area', parent: null },
{ field: 'locality', parent: 'administrative_area_id' },
{ field: 'dependent_locality', parent: 'locality_id' },
];
// Labels when the country's definition has none
const LABELS = {
address_line_1: 'address line 1',
address_line_2: 'address line 2',
administrative_area: 'state',
locality: 'city',
dependent_locality: 'district',
postal_code: 'postal code',
};
// The fields the API compares when it offers a choice
const COMPARED = ['address_line_1', 'address_line_2', 'locality', 'administrative_area', 'postal_code'];
const UNVERIFIED = {
is_verified: false,
verification_provider: null,
verified_at: null,
verification_metadata: null,
needs_review: false,
};
const EMPTY = {
address_line_1: '',
address_line_2: '',
administrative_area: '',
administrative_area_id: null,
locality: '',
locality_id: null,
dependent_locality: '',
dependent_locality_id: null,
postal_code: '',
lat: null,
lon: null,
...UNVERIFIED,
};
// Lookups that just mean "keep typing"
const SILENT_ERRORS = ['incomplete_query', 'zero_results'];
export default function AddressForm({ submitUrl, defaultCountry = 'US' }) {
const [countries, setCountries] = useState([]);
const [country, setCountry] = useState(defaultCountry);
const [definition, setDefinition] = useState(null);
const [options, setOptions] = useState({}); // field => [{ id, name, name_local, ... }]
const [values, setValues] = useState(EMPTY);
const [sentLine1, setSentLine1] = useState(''); // line 1 as last resolved, to skip unchanged blurs
const [choice, setChoice] = useState(null); // a ResolvedAddress with requires_choice
const [review, setReview] = useState([]); // review reason messages of the last result
const [message, setMessage] = useState(null);
const [busy, setBusy] = useState(false);
useEffect(() => {
axios.get(`${API}/countries`).then(({ data }) => setCountries(data.data));
}, []);
// A new country: its address definition, empty fields, the top-level dropdown
useEffect(() => {
setValues(EMPTY);
setOptions({});
setChoice(null);
setReview([]);
setMessage(null);
setSentLine1('');
axios.get(`${API}/countries/${country}`).then(({ data }) => {
setDefinition(data.data.address_definition);
loadOptions(data.data.address_definition, EMPTY);
});
}, [country]);
// Options for each level the country has in the database, once the level above is chosen
async function loadOptions(def, vals) {
const next = {};
for (const { field, parent } of LEVELS) {
if (! def?.[`${field}_level`]) continue;
const parentField = parent?.replace(/_id$/, '');
if (parent && def[`${parentField}_level`] && ! vals[parent]) continue;
const params = parent && vals[parent] ? { field, parent: vals[parent] } : { field };
const { data } = await axios.get(`${API}/countries/${country}/subdivisions`, { params });
next[field] = data.data;
}
setOptions(next);
}
const shown = definition?.template_fields ?? ['address_line_1', 'address_line_2', 'locality', 'postal_code'];
const shows = (field) => shown.includes(field);
const required = (field) => definition?.required_fields?.includes(field) ?? field === 'address_line_1';
const label = (field) => {
const text = definition?.field_labels?.[field] ?? LABELS[field];
return text.charAt(0).toUpperCase() + text.slice(1);
};
// An edit makes the previous verification meaningless
function edit(changes) {
setValues((current) => ({ ...current, ...changes, ...UNVERIFIED }));
setReview([]);
setMessage(null);
}
function pickSubdivision(field, id) {
const option = options[field]?.find((o) => o.id === id);
const changes = { [field]: option?.name ?? '', [`${field}_id`]: option?.id ?? null };
// The levels below belong to the old choice
LEVELS.slice(LEVELS.findIndex((l) => l.field === field) + 1).forEach(({ field: lower }) => {
changes[lower] = '';
changes[`${lower}_id`] = null;
});
const next = { ...values, ...changes, ...UNVERIFIED };
setValues(next);
setReview([]);
setMessage(null);
loadOptions(definition, next);
}
// Take a resolved record into the form, with the dropdowns for its subdivision IDs
function apply(fields) {
const { country_code, ...rest } = fields;
const next = { ...EMPTY, ...rest };
setValues(next);
setSentLine1(next.address_line_1);
loadOptions(definition, next);
}
function handle(result) {
if (! result.success) {
if (! SILENT_ERRORS.includes(result.error.code)) setMessage(result.error.message);
return;
}
if (result.requires_choice) {
setChoice(result);
return;
}
apply(result.fields);
setReview(result.review.reasons.map((r) => r.message));
setMessage(result.verification_error ? `Not verified: ${result.verification_error.message}` : null);
}
async function lookup(endpoint) {
setBusy(true);
setMessage(null);
try {
const { data } = await axios.post(`${API}/${endpoint}`, { ...values, country_code: country });
handle(data);
} catch (error) {
// 419 session expired, 422 invalid request, 429 rate limit: JSON with a message
setMessage(error.response?.data?.message ?? 'The address lookup failed.');
} finally {
setBusy(false);
}
}
function onLine1Blur() {
const line1 = values.address_line_1.trim();
if (line1 === sentLine1 || line1.length < 5 || ! /\d/.test(line1)) return;
setSentLine1(line1);
lookup('resolve/input');
}
function choose(standardized) {
if (standardized) {
apply(choice.fields);
setReview(choice.review.reasons.map((r) => r.message));
} else {
// The user's text and subdivision IDs; coordinates from the lookup.
// Saved unverified and flagged, like "keep my version" in the Filament form
const { lat, lon, ...entered } = choice.original;
apply({
...choice.fields,
...entered,
...UNVERIFIED,
needs_review: true,
verification_metadata: {
review_reasons: [{ code: 'suggested_changes', detail: { fields: choice.changes } }],
},
});
setReview(['Suggested changes to review']);
}
setChoice(null);
}
function submit(event) {
event.preventDefault();
router.post(submitUrl, { ...values, country_code: country }, {
onError: (errors) => setMessage(Object.values(errors)[0]),
});
}
function textField(field, extra = {}) {
if (! shows(field)) return null;
return (
<label key={field}>
{label(field)}
<input
value={values[field] ?? ''}
required={required(field)}
onChange={(e) => edit({ [field]: e.target.value })}
{...extra}
/>
</label>
);
}
function subdivisionField(field) {
if (! shows(field)) return null;
const list = options[field] ?? [];
const id = values[`${field}_id`];
// Free text when the level has no options, or holds text that matched none
if (! list.length || (values[field] && ! id)) {
return textField(field, {
onChange: (e) => edit({ [field]: e.target.value, [`${field}_id`]: null }),
});
}
return (
<label key={field}>
{label(field)}
<select value={id ?? ''} required={required(field)} onChange={(e) => pickSubdivision(field, e.target.value)}>
<option value="">Select…</option>
{list.map((o) => (
<option key={o.id} value={o.id}>{o.name_local ? `${o.name} (${o.name_local})` : o.name}</option>
))}
</select>
</label>
);
}
return (
<form onSubmit={submit}>
<label>
Country
<select value={country} onChange={(e) => setCountry(e.target.value)}>
{countries.map((c) => <option key={c.country_code} value={c.country_code}>{c.name}</option>)}
</select>
</label>
{textField('address_line_1', { onBlur: onLine1Blur })}
{textField('address_line_2')}
{LEVELS.map(({ field }) => subdivisionField(field))}
{textField('postal_code')}
{choice && (
<div role="dialog" aria-label="Choose an address">
<p>We found a standardized version of this address.</p>
<table>
<thead>
<tr><th /><th>You entered</th><th>Standardized</th></tr>
</thead>
<tbody>
{COMPARED.filter(shows).map((field) => (
<tr key={field} className={choice.changes.includes(field) ? 'changed' : undefined}>
<th>{label(field)}</th>
<td>{choice.original[field]}</td>
<td>{choice.fields[field]}</td>
</tr>
))}
</tbody>
</table>
<button type="button" onClick={() => choose(true)}>Use standardized</button>
<button type="button" onClick={() => choose(false)}>Keep mine</button>
</div>
)}
<p aria-live="polite">
{busy && 'Checking address… '}
{values.is_verified && `Verified (${values.verification_provider}). `}
{values.needs_review && 'Needs review: '}
{review.join('; ')}
{message && ` ${message}`}
</p>
<button type="button" disabled={busy || ! values.address_line_1} onClick={() => lookup('verify')}>
Verify
</button>
<button type="submit" disabled={busy || !! choice}>Save address</button>
</form>
);
}Notes on the choices it makes:
- Text and ID together. A dropdown pick stores the option's
nameandid, as the Filament form does (the label with the local name is display only). A resolved record brings both from the server, matched bySubdivisionMatcher. A level whose text matched no subdivision shows as a text field. - Edits clear the verification. The verification describes the values that were verified, so any edit resets
is_verifiedand the other verification fields. The Filament form also flags the recordneeds_review("Edited after verification"); add that if your staff review edited addresses. - Choosing a state clears the city and district, since they belong to the old state.
- "Keep mine" saves the user's version unverified and flagged with the
suggested_changesreview reason, so staff see the suggested changes in the admin panel.
The page and the controller
resources/js/Pages/Addresses/Create.jsx:
import AddressForm from '@/Components/AddressForm';
export default function Create() {
return <AddressForm submitUrl="/addresses" defaultCountry="US" />;
}routes/web.php:
use App\Http\Controllers\AddressController;
Route::middleware('auth')->group(function () {
Route::get('/addresses/create', [AddressController::class, 'create']);
Route::post('/addresses', [AddressController::class, 'store']);
});app/Http/Requests/StoreAddressRequest.php. The form posts Address columns, so the validated data goes straight into create():
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreAddressRequest extends FormRequest
{
public function rules(): array
{
return [
'country_code' => ['required', 'string', 'size:2'],
'address_line_1' => ['required', 'string', 'max:255'],
'address_line_2' => ['nullable', 'string', 'max:255'],
'administrative_area' => ['nullable', 'string', 'max:255'],
'administrative_area_id' => ['nullable', 'string', 'size:26'],
'locality' => ['nullable', 'string', 'max:255'],
'locality_id' => ['nullable', 'string', 'size:26'],
'dependent_locality' => ['nullable', 'string', 'max:255'],
'dependent_locality_id' => ['nullable', 'string', 'size:26'],
'postal_code' => ['nullable', 'string', 'max:20'],
'lat' => ['nullable', 'numeric', 'between:-90,90'],
'lon' => ['nullable', 'numeric', 'between:-180,180'],
// Verification state from the API. Only for signed-in users: see below
'is_verified' => ['boolean'],
'needs_review' => ['boolean'],
'verification_provider' => ['nullable', 'string', 'max:50'],
'verified_at' => ['nullable', 'date'],
'verification_metadata' => ['nullable', 'array'],
];
}
}app/Http/Controllers/AddressController.php:
namespace App\Http\Controllers;
use App\Http\Requests\StoreAddressRequest;
use Inertia\Inertia;
class AddressController extends Controller
{
public function create()
{
return Inertia::render('Addresses/Create');
}
public function store(StoreAddressRequest $request)
{
$request->user()->addresses()->create($request->validated());
return redirect('/addresses');
}
}addresses() comes from the HasAddresses trait on the user model.
Public forms. This controller trusts the verification state the browser sends, which is fine behind auth: it came from the API in the same session, and a user who forges it only affects their own records. On a public form (checkout, sign-up), leave the five verification rules out, so validated() never contains them. The address is then saved unverified; verify it on the server with AddressResolver::verify() before saving, or let silent verification do it. See Saving the address.
Extending it
- Address autocomplete. Add Google's Places search box and send the selection to
resolve/place: Places Autocomplete in your own form. - Coordinates after a city change. The Filament form calls
resolve/locatewhen the city changes, so the coordinates follow the new city (a geocode, no verification). Call it frompickSubdivision()forlocalityand takefields.latandfields.lonfrom the result. - Postal code check.
POST /address-api/postal-codesays whether the code matches the country's format (and, for DE, ES, FR, IT and NL, which state it belongs to). - Live preview.
POST /address-api/formatreturns the address as the country writes it, international and local. - Map preview.
<img src={/filament-address/map-image?lat=${values.lat}&lng=${values.lon}} />shows the static map through the package's proxy (Google's terms allow Google data on a Google map only). - Field order. The example shows the fields in a fixed order; the country's
template_defaultgives the order the country writes them in.