Inertia — Laravel Routes, JavaScript Pages
Some teams love React or Vue for building screens, but do not want to design, version and document a whole JSON API just to feed their own website. Inertia is the bridge. Laravel keeps routing and controllers. React or Vue draws the page. The data passes straight between them.
The rule
The controller names a page component and passes props; Inertia does the rest.
In a Blade app a controller returns view(...). In an Inertia app it returns Inertia::render(...):
use Inertia\Inertia;
Route::get('/books', function () {
return Inertia::render('books/index', [
'books' => Book::all(),
]);
});'books/index' names a component file, such as resources/js/pages/books/index.tsx in the React kit. The array becomes that component's props:
export default function Index({ books }) {
return <ul>{books.map(b => <li key={b.id}>{b.title}</li>)}</ul>;
}What happens on the wire:
- First visit: Laravel returns a full HTML page with the JavaScript app and the first page's data embedded in it.
- Later clicks: Inertia's
<Link>sends a background request with anX-Inertiaheader. Laravel runs the same route and controller, but replies with JSON: the component name, its props and the URL. - The client swaps in the new component. No full reload, and it feels like a single-page app.
Forms work the same way. You post to a normal Laravel route. If validation fails, the errors come back as props, and the form shows them without losing what the member typed.