← All guides

Published · 6 min read

Inertia and Vue in Laravel Rust, for Laravel developers

Rendering Inertia pages from Rust handlers, props, deferred and on-scroll data, shared data, forms, flash messages and testing, with Vue page components.

  • inertia
  • vue
  • frontend
On this page
  1. React by default, Vue by choice
  2. Rendering a page
  3. The Vue page
  4. Handling the form
  5. Shared data
  6. Other things you’ll reach for
  7. Testing a page

If you build Laravel PHP apps with Inertia, the frontend half stays the same. Your page components, <Link>, <Form>, useForm, deferred props and polling are Inertia’s, not Laravel’s, and they talk to a Laravel Rust backend exactly as they talk to a PHP one. What changes is the server half: Inertia::render becomes inertia::render, and a few things that are runtime checks in PHP become compile-time ones.

The pages here belong to a book club. Each meeting page shows the book, who’s coming (loaded after the page appears), the discussion notes (loaded when you scroll to them) and an RSVP form.

The book club’s Meetings/Show page. The Rust handler passes three props: meeting, rsvps wrapped in inertia::defer and notes wrapped in inertia::optional. In the Vue page, the meeting title arrives with the first response, the RSVP list inside <Deferred data="rsvps"> is fetched right after the page mounts, and the discussion notes inside <WhenVisible data="notes" :buffer="300"> are fetched only when the reader scrolls within 300px of them.

React by default, Vue by choice

New Laravel Rust apps come set up with Inertia, React, TypeScript and Tailwind. The Laravel Rust docs show React examples and point to Inertia’s own documentation for the Vue and Svelte adapters. There’s no Vue starter for Laravel Rust described in the docs yet, so moving a new app to Vue is a frontend change you make yourself:

  • The server side doesn’t care. A handler names a page component as a string; it renders the same way whichever adapter the browser uses.
  • The client uses @inertiajs/vue3, which exports the same pieces as the React adapter: Link, Form, useForm, Deferred, WhenVisible, usePoll, usePage and more. The docs’ live props need the Inertia client at 3.11 or later, and the Vue adapter is published at that version.
  • The root view is React-specific out of the box. resources/views/app.html calls vite_react_refresh() and points vite(...) at app.tsx and .tsx page files, so those lines change along with your Vite setup.

Everything below works the same with React; only the component code differs.

Rendering a page

In Laravel PHP:

public function show(Meeting $meeting)
{
    return Inertia::render('Meetings/Show', [
        'meeting' => $meeting,
        'rsvps' => Inertia::defer(fn () => $meeting->rsvps()->get()),
        'notes' => Inertia::optional(fn () => $meeting->notes()->get()),
    ]);
}

In Laravel Rust:

// src/http/handlers/meetings.rs
use laravel::inertia::{self, Page, props};

use crate::models::{Meeting, Note, Rsvp};

pub async fn show(meeting: Meeting) -> Page {
    let meeting_id = meeting.id;

    inertia::render("Meetings/Show", props! {
        meeting,
        rsvps => inertia::defer(async move || {
            Rsvp::query().filter(Rsvp::meeting_id.eq(meeting_id)).get().await
        }),
        notes => inertia::optional(async move || {
            Note::query().filter(Note::meeting_id.eq(meeting_id)).get().await
        }),
    })
}

What’s different:

  • props! instead of an array. A variable on its own (meeting) becomes a prop of the same name; name => value sets one explicitly.
  • Keys keep the casing you write. starts_at stays starts_at. If your Vue code expects camelCase, write startsAt => ....
  • Callbacks can’t borrow from the handler. Deferred and optional props run after the handler returns, so they capture owned values with async move. That’s why the handler copies meeting.id into meeting_id first.
  • Typed structs work too. Any Serialize struct can replace props! if you prefer a named type for a page’s props.
  • Hidden fields are enforced. Every prop reaches the browser, so mark private model fields #[serde(skip)]. A password hash can’t be serialized at all, so it can’t leak into a page.

inertia::defer omits the prop from the first response and fetches it straight after the page mounts. inertia::optional is only sent when the client asks for it, which pairs with <WhenVisible>. Group slow deferred props with .group("rsvps") to fetch them in parallel, and add .rescue() so one failing prop doesn’t stop the rest.

The Vue page

<!-- resources/js/pages/Meetings/Show.vue -->
<script setup lang="ts">
import { Deferred, Form, WhenVisible } from '@inertiajs/vue3'

defineProps<{
  meeting: { id: number; book_title: string; starts_at: string }
  rsvps?: { id: number; member_name: string; guests: number }[]
  notes?: { id: number; body: string }[]
}>()
</script>

<template>
  <article>
    <h1>{{ meeting.book_title }}</h1>

    <Deferred data="rsvps">
      <template #fallback>
        <p>Checking who's coming…</p>
      </template>
      <ul>
        <li v-for="rsvp in rsvps" :key="rsvp.id">
          {{ rsvp.member_name }} <span v-if="rsvp.guests">+{{ rsvp.guests }}</span>
        </li>
      </ul>
    </Deferred>

    <Form :action="`/meetings/${meeting.id}/rsvps`" method="post" #default="{ errors, processing }">
      <label>
        Bringing guests?
        <input type="number" name="guests" min="0" max="3" value="0" />
      </label>
      <p v-if="errors.guests">{{ errors.guests }}</p>
      <button type="submit" :disabled="processing">I'm coming</button>
    </Form>

    <WhenVisible data="notes" :buffer="300">
      <template #fallback>
        <p>Loading the discussion notes…</p>
      </template>
      <p v-for="note in notes" :key="note.id">{{ note.body }}</p>
    </WhenVisible>
  </article>
</template>

The component has no Rust-specific code in it.

Handling the form

use laravel::inertia;
use laravel::model::create;
use laravel::prelude::*;

use crate::models::{Meeting, Rsvp, User};

#[laravel::input(fills = Rsvp)]
#[validate(authenticated)]
pub struct NewRsvp {
    #[validate(required, max_value(3))]
    pub guests: u32,
}

pub async fn store(
    Authenticated(member): Authenticated<User>,
    meeting: Meeting,
    Valid(input): Valid<NewRsvp>,
) -> laravel::Result<Redirect> {
    create!(Rsvp { meeting: &meeting, user: &member, ..input }).await?;

    inertia::flash("toast", "See you there!")?;

    Ok(Redirect::back())
}

When validation fails, Laravel redirects back and fills the page’s errors prop, so the <Form> above shows the message next to the field and keeps what was typed, as with PHP. For an error no rule catches, such as a meeting that’s already full, invalid!(guests => "This meeting is full.") does the same from inside the handler.

The fill struct is also the mass-assignment guard: the request can set guests and nothing else. meeting and user come from the route and the session, and meeting: &meeting fills meeting_id through the belongs_to relationship.

inertia::flash puts the toast in the page’s flash field rather than in its props, so it doesn’t reappear when someone presses the back button. In a Vue layout, read it from usePage().flash.

After a PUT, PATCH or DELETE, Laravel turns a 302 redirect into a 303 for you, as Inertia requires. To send the browser to another site, such as a payment page, return inertia::location(url).

Shared data

PHP’s HandleInertiaRequests::share() has a direct equivalent, also called HandleInertiaRequests, in src/http/middleware:

impl inertia::Middleware for HandleInertiaRequests {
    async fn share(&self, request: &Request) -> laravel::Result<Props> {
        let user: Option<User> = request.user().await?;

        Ok(props! {
            auth => json!({ "user": user }),
        })
    }
}

share runs before your handler. If a shared value can change during the request, such as a basket count, wrap it in inertia::lazy so it’s worked out when the page renders. For the same reason, redirect after logging someone in or out, so the next page gets the new user.

Other things you’ll reach for

Laravel PHP Laravel Rust
Inertia::render('Page', [...]) inertia::render("Page", props! { ... })
Inertia::defer(fn () => ...) inertia::defer(async move || ...)
Inertia::optional(...) inertia::optional(...)
Inertia::always(...) inertia::always(...)
Inertia::merge(...) inertia::merge(...)
Inertia::location($url) inertia::location(url)
Route::inertia('/about', 'About') route.inertia("/about", "About")
Inertia::clearHistory() inertia.clear_history()
php artisan inertia:start-ssr node bootstrap/ssr/app.js, with INERTIA_SSR=true

Polling (usePoll), prefetching (<Link prefetch>), infinite scroll (inertia::scroll) and history encryption all work as you’d expect. Error pages render through an Inertia component you name in error_page, and new apps add a fallback route so 404s use it too.

Tip: restart after building assets in production. Outside debug mode, Laravel caches the root view and Vite’s manifest when the app starts. After npm run build, restart the binary.

Testing a page

#[laravel::test]
async fn the_meeting_page_defers_the_rsvps(app: Application) -> laravel::Result<()> {
    let meeting = Meeting::factory().create().await?;

    app.get(&format!("/meetings/{}", meeting.id))
        .await
        .assert_inertia()
        .component("Meetings/Show")
        .has("meeting")
        .missing("rsvps");

    Ok(())
}

assert_inertia() is PHP’s assertInertia(), with has, missing, equals, has_count, deferred and scoped assertions. component(...) also checks that the page file exists in resources/js/pages, so a misspelled component name fails the test. The docs don’t say how that check finds a .vue file, so confirm it in your own app after switching.