Laravel + Inertia.js + React
Comprehensive patterns for building modern monolithic applications with Laravel, Inertia.js, and React. Contains 27 rules across 5 categories, written for Inertia v3.
When to Apply
Reference these guidelines when:
- Creating Inertia page components
- Handling forms with useForm hook
- Managing shared data and authentication
- Implementing persistent layouts
- Navigating between pages
Using with Laravel for Rust
A Laravel for Rust app (laravel-rust crate) whose frontend is Inertia React v3, as in both official starters (the base app and laravel/laravel-rust-flux-react ship @inertiajs/react v3), uses the React patterns in these rules: page components, <Form> and useForm, <Link> and router, layouts, usePage, and the client half of deferred props and partial reloads. Adapt these React details, and translate the PHP server code.
React side
- No Ziggy: there is no
route()helper for the frontend. Many examples call it (15 rules, such asnav-link-component,nav-programmaticandform-useform-basic); write the app's URL instead, keeping parameters as path segments or query data (route('posts.show', post.id)becomes`/posts/${post.id}`;route('users.index', { status: 'active' })becomes'/users?status=active'). For active links, compare withusePage().urlinstead ofroute().current(..). The official Flux starter kit writes URL strings this way.shared-ziggy-routesdoes not apply - Flash:
inertia::flash(..)"delivers the value in the page'sflashfield rather than its props", so readusePage().flash(orpage.flashin a visit callback), with the key the server flashed, notprops.flash. Whereshared-flash-messagesandnav-programmaticreadprops.flash.success, a handler that callsinertia::flash("toast", ..)is read asusePage().flash.toast; flash values are typedunknown, so check the type before rendering - Shared props are what the app shares: the base starter shares
nameandstatus, and every page also getserrorsand aheadprop; the Flux starter addsauth.user, which isnullfor guests and carries the user's columns (id,name,email,email_verified_at, timestamps) with no roles or permissions. Type and read only whatHandleInertiaRequests::sharesends: dropflashandziggyfrom thePagePropsinpage-props-typing, share role and permission arrays yourself before usingusePermissionsfromshared-auth-user, and share theapp,config,featuresandsettingsprops before usingshared-app-config. The examples that readauth.user.name(page-component-structure,page-default-layout,layout-persistent) assume a signed-in page in an app that sharesauth; elsewhere guardauth?.user. The Flux starter declares shared props onInertiaConfiginresources/js/types/inertia.d.ts - Paginators: a Rust
Paginatorserializesdata,total,current_pageand the page URLs at the top level, withlinksas an array of{ url, label, page, active }entries (pageisnullon a disabled Previous/Next and left out of...gap entries); there is nometaobject. That is thePaginatedData<T>type inpage-props-typing. Its page links keep only thepageparameter ("navigating to page 2 drops active search or sort filters"), so the filtered lists innav-preserve-stateandnav-replace-historyneed.with_query_string()or.appends(&filters)on the paginator - Head: the starters render head metadata on the server (
laravel::head) and setserverHead: trueinapp.tsx, so crawlers see titles and social tags without JavaScript. Set the title, description, Open Graph tags and JSON-LD withhead::mergein the handler, leave out the clienttitlecallback, and "reserve Inertia's<Head>component for tags the server doesn't render" (page-head-management) - Pages: the starters have no
resolveinapp.tsx; the Inertia Vite plugin resolves pages from lowercaseresources/js/pages/, and the Flux starter keeps layouts inresources/js/layouts/. Keep that, skip theimport.meta.glob('./Pages/**')resolvers inlayout-persistent, and set a default layout with thelayoutoption - File uploads: Inertia sends real
PUTandPATCHrequests, soput(url)with files works; a form that spoofs the method must put_methodbefore its file inputs, asform-file-uploadsdoes
Server side
| In this skill (Laravel PHP) | In Laravel for Rust (laravel-rust 0.2.x) |
|---|---|
Inertia::render('Posts/Show', [...]) |
inertia::render("Posts/Show", props! { post => PostSummary::from(post) }) with a response struct; props! { post } would send every column (see laravel-rust-best-practices, http-responses-send-only-needed) |
HandleInertiaRequests::share() in PHP |
impl inertia::Middleware for HandleInertiaRequests { async fn share(&self, request: &Request) -> laravel::Result<Props> } in src/http/middleware/ |
Session flash shared as props.flash |
inertia::flash("toast", "Saved")? before the redirect |
Inertia::defer, Inertia::optional, Inertia::merge, Inertia::always, Inertia::once |
inertia::defer, inertia::optional, inertia::merge, inertia::always, inertia::once, plus inertia::lazy |
Inertia::defer(fn () => .., 'charts') and rescue: true |
inertia::defer(..).group("charts") and .rescue() |
| Prop names | "Keys keep the exact casing you write, so can_edit stays can_edit"; write canEdit => can_edit if the frontend expects camelCase |
| Models in props | Models serialize every column by default; skip private fields with #[serde(skip)] or send a response struct |
A controller returning JSON for useHttp (nav-usehttp-requests) |
A handler returning Json(..). Invalid input comes back as 422 JSON when the request expects JSON: an api route, an Accept: application/json header (which useHttp sends), or a non-Inertia XHR that accepts anything. Keep session-authenticated endpoints in the web group |
| Validation errors on an Inertia form | The same contract: an Inertia visit does not expect JSON, so an invalid Valid<T> on a web route with a session redirects back with the errors and old input, and form.errors and <Form> errors work unchanged. Only validation failures redirect this way; other errors keep their own response |
For the Rust server side, also read the app's inertia-frontend skill in .agents/skills/, <docs>/inertia.md and <docs>/head.md bundled with the crate, and laravel-rust-best-practices.
Using with Laravel for Go
A Laravel for Go app (go.laravel.com module) is set up with Inertia React v3 from the start: the starter app (laravel/go) ships @inertiajs/react v3 with TypeScript and Vite, renders pages from inertia.Render and mounts them in resources/js/app.tsx. It uses the React patterns in these rules: page components, <Form> and useForm, <Link> and router, layouts, usePage, and the client half of deferred props and partial reloads. Adapt these React details, and translate the PHP server code.
React side
- No Ziggy or Wayfinder: Go has named routes, but only on the server (
urls.Routein a handler,routein a template,web.RedirectRoute); the starter'spackage.jsonhas neither Ziggy nor Wayfinder, and the bundled docs' React examples write URL strings (<Link href="/dashboard">,post("/posts")). In the 15 rules that callroute()(such asnav-link-component,nav-programmaticandform-useform-basic), write the app's URL instead, keeping parameters as path segments or query data (route('posts.show', post.id)becomes`/posts/${post.id}`;route('users.index', { status: 'active' })becomes'/users?status=active'). For active links, compare withusePage().urlinstead ofroute().current(..). When a page needs a URL only the server can build, such as a signed link, build it withurls.Routeorurls.SignedRoutein the handler and pass it as a prop.shared-ziggy-routesdoes not apply - Flash:
inertia.Flash(r, key, value)"delivers the value in the page'sflashfield rather than its props", so readusePage().flash(orpage.flashin a visit callback), with the key the server flashed, notprops.flash. Whereshared-flash-messagesandnav-programmaticreadprops.flash, a handler that callsinertia.Flash(r, "toast", ..)is read asusePage().flash.toast; "Inertia types flash values asunknownby default", so check the type before rendering. Session flash set withWithon a redirect is not page flash: the starter shares the session'sstatus, so "The destination page receives the notice asprops.status, not in itsflashfield" - Shared props are what the app shares: the starter's
sharefunction inbootstrap/app.gosendsnameandstatus, and every page also getserrorsand aheadprop. It shares noauth: add"auth.user"tosharefirst (the docs usemodels.CurrentUser(r), which sends the user's JSON fieldsid,name,email,email_verified_at,created_atandupdated_at, with no roles or permissions; "Pages receivenullfor guests"). Type and read only whatsharesends: dropflashandziggyfrom thePagePropsinpage-props-typing, share role and permission arrays yourself before usingusePermissionsfromshared-auth-user(a dotted key such as"auth.permissions"nests insideauth), and share theapp,config,featuresandsettingsprops before usingshared-app-config. The examples that readauth.user.name(page-component-structure,page-default-layout,layout-persistent) assume a signed-in page in an app that sharesauth; elsewhere guardauth?.user - Paginators: a Go paginator from
Paginateserializesdata,total,current_pageand the page URLs at the top level, withlinksas an array of{ url, label, page, active }entries (pageisnullon a disabled Previous/Next and left out of...gap entries); there is nometaobject. That is thePaginatedData<T>type inpage-props-typing. Its page links keep only thepageparameter ("navigating to page 2 drops an active search or sort order"), so the filtered lists innav-preserve-stateandnav-replace-historyneed.WithQueryString()or.Appends(url.Values{..})on the paginator.SimplePaginateandCursorPaginatereturn other shapes ("SimplePaginatoromitslast_page,last_page_url,links, andtotal") - Head: the starter renders head metadata on the server (
{{.Head}}inresources/views/app.html) and setsserverHead: trueinapp.tsx, so crawlers see titles and social tags without JavaScript. Set the title, description and social tags withhead.Mergein the handler, leave out the clienttitlecallback, and "keep Inertia's<Head>component for tags the server doesn't render" (page-head-management) - Pages: the starter has no
resolveinapp.tsx; the Inertia Vite plugin resolves pages from lowercaseresources/js/pages/("Page components live inresources/js/pages"), and the app'sinertia-frontendskill puts layouts inresources/js/layouts/. Keep that, skip theimport.meta.glob('./Pages/**')resolvers inlayout-persistent, and set a default layout with thelayoutoption - File uploads: Inertia sends real
PUT,PATCHandDELETErequests, "so they don't need_method", andput(url)with files works; a form that spoofs the method must put_methodbefore its file inputs, "because Laravel only looks for the field at the start of the body", asform-file-uploadsdoes - CSRF: as in Laravel PHP, every
webresponse sets anXSRF-TOKENcookie that the Inertia client sends back asX-XSRF-TOKEN, so<Form>,useForm,routeranduseHttpneed nothing extra. The starter's root view has nocsrf-tokenmeta tag; a barefetchneeds<meta name="csrf-token" content="{{csrfToken}}">inresources/views/app.htmland anX-CSRF-TOKENheader
Server side
| In this skill (Laravel PHP) | In Laravel for Go (go.laravel.com 0.2.x) |
|---|---|
Inertia::render('Posts/Show', [...]) |
inertia.Render("Posts/Show", inertia.Props{"post": post}), or inertia.RenderPage with a struct whose json tags name the props; route.Inertia("/about", "About") for a page with no handler logic |
HandleInertiaRequests::share() in PHP |
The Share function of inertia.Middleware in bootstrap/app.go, func share(r *web.Request) (inertia.Props, error), plus inertia.Share(r, key, value) from a route group's middleware or a handler. "Share runs on every request before your handler", so wrap a value the handler changes in inertia.Lazy (see laravel-go-best-practices, http-inertia-shared-props) |
Session flash shared as props.flash |
inertia.Flash(r, "toast", "Saved") before return web.Back() or another redirect |
Inertia::optional(fn () => ..) |
inertia.Optional(fn), "Sent only when a partial reload explicitly requests it." Not inertia.Lazy: Go's Lazy is "Evaluated only when the response includes the prop", and a first visit includes it |
Inertia::defer, Inertia::merge, Inertia::always, Inertia::once |
inertia.Defer, inertia.Merge (and inertia.DeepMerge), inertia.Always, inertia.Once, plus inertia.Scroll for <InfiniteScroll>. A prop function is func(context.Context) (T, error), so a query's Get fits as it is |
Inertia::defer(fn () => .., 'charts') and rescue: true |
inertia.Defer(fn, "charts") and .Rescue() |
| Prop names | "Keys keep the exact casing you write", so can_edit stays can_edit; write "canEdit": canEdit if the frontend expects camelCase. A dotted key such as "auth.permissions" sets a nested prop |
| Models in props | A model encodes with its json tags (the starter's User sends email_verified_at); skip private fields with json:"-", or send a response struct (see laravel-go-best-practices, http-responses-send-only-needed) |
redirect()->route('posts.index') after a form |
web.RedirectRoute("posts.index"), web.Redirect("/posts") or web.Back(). After a PUT, PATCH or DELETE, inertia.Middleware turns a 302 into a 303, so the browser follows it with GET |
A controller returning JSON for useHttp (nav-usehttp-requests) |
A handler returning web.JSON(..). Invalid input comes back as 422 JSON ({"message": .., "errors": {"title": ["The title field is required."]}}) when the request expects JSON: a route in routes/api.go, an Accept header that prefers JSON (which useHttp sends), or an X-Requested-With: XMLHttpRequest request whose Accept allows anything. Keep session-authenticated endpoints in routes/web.go |
| Validation errors on an Inertia form | The same contract: an Inertia visit does not expect JSON, so r.Validate with web.Fail(err) redirects back and "populates the page's errors prop with each field's first message", and form.errors and <Form> errors work unchanged. AllErrors: true on inertia.Middleware sends lists instead; web.Invalid("name", "..") adds an error the rules did not catch; a named bag arrives as errors.login.email |
For the Go server side, also read the app's inertia-frontend skill in .agents/skills/, <docs>/inertia.md, <docs>/head.md and <docs>/pagination.md bundled with the module, and laravel-go-best-practices; to port a Laravel PHP Inertia app, read laravel-php-to-go (view-inertia).
Rule Categories by Priority
| Priority | Category | Impact | Prefix | Rules |
|---|---|---|---|---|
| 1 | Page Components | CRITICAL | page- |
7 |
| 2 | Forms & Validation | CRITICAL | form- |
9 |
| 3 | Navigation | HIGH | nav- |
6 |
| 4 | Shared Data | HIGH | shared- |
4 |
| 5 | Layouts | MEDIUM | layout- |
1 |
Quick Reference
1. Page Components (CRITICAL)
page-component-structure- Standard page component patternpage-props-typing- Type page props from Laravelpage-head-management- Title and meta tags with Headpage-default-layout- Assign layouts to pagespage-scroll-preservation- Keep scroll position across visitspage-partial-reloads- Reload only the props that changed,usePollpage-deferred-props-Inertia::defer()with<Deferred>
2. Forms & Validation (CRITICAL)
form-useform-basic- Basic useForm usageform-useform-hook- useForm methods and stateform-component-<Form>component for simple formsform-validation-errors- Display Laravel validation errorsform-file-uploads- File uploads with useFormform-progress-indicator- Upload and submit progressform-transform-data- Transform data before submitform-reset-handling- Reset fields and errorsform-dirty-tracking- Track and warn on unsaved changes
3. Navigation (HIGH)
nav-link-component- Use Link for navigationnav-programmatic- Navigate with the routernav-external-links- External links and downloadsnav-preserve-state- Preserve scroll and statenav-replace-history- Replace vs push historynav-usehttp-requests-useHttpfor JSON requests that are not page visits
4. Shared Data (HIGH)
shared-auth-user- Access authenticated usershared-flash-messages- Handle flash messagesshared-ziggy-routes- Named routes in JavaScript (Ziggy, or Wayfinder in starter-kit apps)shared-app-config- App configuration and feature flags
5. Layouts (MEDIUM)
layout-persistent- Persistent, nested and default layouts, layout props
Inertia v3 Notes
Check these when a project moves from Inertia v2 to v3 (see the v3 upgrade guide):
- Requires PHP 8.2+, Laravel 11.35+ and React 19. Laravel 13 itself needs PHP 8.3+.
- Axios is no longer shipped or required; Inertia has its own HTTP client. Use
useHttpfor non-visit requests.qsandlodash-esare no longer bundled: install them yourself if the app imports them. Inertia::lazy()andLazyPropare removed: useInertia::optional().router.cancel()is nowrouter.cancelAll().- The
invalidevent is nowhttpExceptionandexceptionis nownetworkError. hideProgress()/revealProgress()are removed: useprogress.hide()/progress.reveal()from@inertiajs/react.- The
inertiaattribute on head elements is nowdata-inertia. - The initial page data is always in a
<script type="application/json">element; thedata-pageattribute on the rootdivis gone. Delete thefutureblock fromcreateInertiaApp. - Arrow-function components assigned to
.layoutmust be wrapped in an array:Page.layout = [Layout]. <Deferred>keeps existing content during partial reloads; use itsreloadingslot prop.useFormprocessingandprogressreset only inonFinish.- Packages are ESM-only and target ES2022.
- Republish the config and clear views:
php artisan vendor:publish --provider="Inertia\\ServiceProvider" --forcethenphp artisan view:clear.
Essential Patterns
Page Component with TypeScript
// resources/js/Pages/Posts/Index.tsx
import { Head, Link } from '@inertiajs/react'
interface Post {
id: number
title: string
excerpt: string
created_at: string
author: {
id: number
name: string
}
}
interface Props {
posts: {
data: Post[]
links: { url: string | null; label: string; active: boolean }[]
}
filters: {
search?: string
}
}
export default function Index({ posts, filters }: Props) {
return (
<>
<Head title="Posts" />
<div className="container mx-auto py-8">
<h1 className="text-2xl font-bold mb-6">Posts</h1>
<div className="space-y-4">
{posts.data.map((post) => (
<article key={post.id} className="p-4 bg-white rounded-lg shadow">
<Link href={route('posts.show', post.id)}>
<h2 className="text-xl font-semibold hover:text-blue-600">
{post.title}
</h2>
</Link>
<p className="text-gray-600 mt-2">{post.excerpt}</p>
<p className="text-sm text-gray-400 mt-2">
By {post.author.name}
</p>
</article>
))}
</div>
</div>
</>
)
}
Form with useForm
// resources/js/Pages/Posts/Create.tsx
import { Head, useForm, Link } from '@inertiajs/react'
import { FormEvent } from 'react'
interface Category {
id: number
name: string
}
interface Props {
categories: Category[]
}
export default function Create({ categories }: Props) {
const { data, setData, post, processing, errors, reset } = useForm({
title: '',
body: '',
category_id: '',
})
const handleSubmit = (e: FormEvent) => {
e.preventDefault()
post(route('posts.store'), {
onSuccess: () => reset(),
})
}
return (
<>
<Head title="Create Post" />
<form onSubmit={handleSubmit} className="max-w-2xl mx-auto py-8">
<div className="mb-4">
<label htmlFor="title" className="block font-medium mb-1">
Title
</label>
<input
id="title"
type="text"
value={data.title}
onChange={(e) => setData('title', e.target.value)}
className="w-full border rounded px-3 py-2"
/>
{errors.title && (
<p className="text-red-500 text-sm mt-1">{errors.title}</p>
)}
</div>
<div className="mb-4">
<label htmlFor="category" className="block font-medium mb-1">
Category
</label>
<select
id="category"
value={data.category_id}
onChange={(e) => setData('category_id', e.target.value)}
className="w-full border rounded px-3 py-2"
>
<option value="">Select a category</option>
{categories.map((category) => (
<option key={category.id} value={category.id}>
{category.name}
</option>
))}
</select>
{errors.category_id && (
<p className="text-red-500 text-sm mt-1">{errors.category_id}</p>
)}
</div>
<div className="mb-4">
<label htmlFor="body" className="block font-medium mb-1">
Content
</label>
<textarea
id="body"
value={data.body}
onChange={(e) => setData('body', e.target.value)}
rows={10}
className="w-full border rounded px-3 py-2"
/>
{errors.body && (
<p className="text-red-500 text-sm mt-1">{errors.body}</p>
)}
</div>
<div className="flex gap-4">
<button
type="submit"
disabled={processing}
className="px-4 py-2 bg-blue-600 text-white rounded disabled:opacity-50"
>
{processing ? 'Creating...' : 'Create Post'}
</button>
<Link
href={route('posts.index')}
className="px-4 py-2 border rounded"
>
Cancel
</Link>
</div>
</form>
</>
)
}
Persistent Layout
// resources/js/Layouts/AppLayout.tsx
import { Link, usePage } from '@inertiajs/react'
import { ReactNode } from 'react'
interface Props {
children: ReactNode
}
export default function AppLayout({ children }: Props) {
const { auth } = usePage<{ auth: { user: { name: string } } }>().props
return (
<div className="min-h-screen bg-gray-100">
<nav className="bg-white shadow">
<div className="container mx-auto px-4 py-3 flex justify-between">
<Link href="/" className="font-bold">
My App
</Link>
<span>Welcome, {auth.user.name}</span>
</div>
</nav>
<main className="container mx-auto px-4 py-8">
{children}
</main>
</div>
)
}
// resources/js/Pages/Dashboard.tsx
import AppLayout from '@/Layouts/AppLayout'
export default function Dashboard() {
return <h1>Dashboard</h1>
}
// Assign persistent layout (or set a default for all pages with
// createInertiaApp({ layout: () => AppLayout }) - see layout-persistent)
Dashboard.layout = (page: ReactNode) => <AppLayout>{page}</AppLayout>
Laravel Controller
<?php
namespace App\Http\Controllers;
use App\Http\Requests\StorePostRequest;
use App\Models\Post;
use App\Models\Category;
use Illuminate\Http\RedirectResponse;
use Inertia\Inertia;
use Inertia\Response;
class PostController extends Controller
{
public function index(): Response
{
return Inertia::render('Posts/Index', [
'posts' => Post::with('author:id,name')
->latest()
->paginate(10),
'filters' => request()->only('search'),
]);
}
public function create(): Response
{
return Inertia::render('Posts/Create', [
'categories' => Category::all(['id', 'name']),
]);
}
public function store(StorePostRequest $request): RedirectResponse
{
$post = Post::create([
...$request->validated(),
'user_id' => auth()->id(),
]);
return redirect()
->route('posts.show', $post)
->with('success', 'Post created successfully.');
}
public function show(Post $post): Response
{
return Inertia::render('Posts/Show', [
'post' => $post->load('author', 'category'),
]);
}
}
Shared Data (HandleInertiaRequests)
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Request;
use Inertia\Middleware;
class HandleInertiaRequests extends Middleware
{
public function share(Request $request): array
{
return array_merge(parent::share($request), [
'auth' => [
'user' => $request->user() ? [
'id' => $request->user()->id,
'name' => $request->user()->name,
'email' => $request->user()->email,
] : null,
],
'flash' => [
'success' => $request->session()->get('success'),
'error' => $request->session()->get('error'),
],
]);
}
}
Flash Messages Component
// resources/js/Components/FlashMessages.tsx
import { usePage } from '@inertiajs/react'
import { useEffect, useState } from 'react'
export default function FlashMessages() {
const { flash } = usePage<{
flash: { success?: string; error?: string }
}>().props
const [visible, setVisible] = useState(false)
useEffect(() => {
if (flash.success || flash.error) {
setVisible(true)
const timer = setTimeout(() => setVisible(false), 3000)
return () => clearTimeout(timer)
}
}, [flash])
if (!visible) return null
return (
<div className="fixed top-4 right-4 z-50">
{flash.success && (
<div className="bg-green-500 text-white px-4 py-2 rounded shadow">
{flash.success}
</div>
)}
{flash.error && (
<div className="bg-red-500 text-white px-4 py-2 rounded shadow">
{flash.error}
</div>
)}
</div>
)
}
How to Use
Read individual rule files for detailed explanations and code examples:
rules/form-useform-basic.md
rules/page-props-typing.md
rules/layout-persistent.md
Project Structure
laravel-inertia-react/
├── SKILL.md # This file - overview and examples
├── README.md # Quick reference guide
├── AGENTS.md # Integration guide for AI agents
├── metadata.json # Skill metadata and references
└── rules/
├── _sections.md # Rule categories and priorities
├── _template.md # Template for new rules
├── page-*.md # Page component patterns (7 rules)
├── form-*.md # Form handling patterns (9 rules)
├── nav-*.md # Navigation patterns (6 rules)
├── shared-*.md # Shared data patterns (4 rules)
└── layout-*.md # Layout patterns (1 rule)
References
- Inertia.js Documentation - Official Inertia.js docs
- Laravel Documentation - Laravel framework docs
- React Documentation - Official React docs
- Inertia.js v3 Upgrade Guide - Breaking changes from v2
- Ziggy - Laravel route helper for JavaScript
- Wayfinder - Type-safe routes used by Laravel's starter kits
License
MIT License. This skill is provided as-is for educational and development purposes.
Metadata
- Version: 1.3.1
- Last Updated: December 2026
- Maintainer: Asyraf Hussin
- Rule Count: 27 rules across 5 categories
- Tech Stack: PHP 8.2+ (8.3+ for Laravel 13), Laravel 11.35+ (13.x), Inertia.js 3.x, React 19+, Vite 8, TypeScript 6+
