Home: useHttp
The home page counts the ideas and comments, and has a newsletter box built with useHttp: it posts JSON to /api/subscribers, shows the 422 errors, and never leaves the page.
The page
gts
import Component from '@glimmer/component';
import type { TOC } from '@ember/component/template-only';
import { on } from '@ember/modifier';
import { bind, Link, type PageSignature, useHttp } from 'inertia-ember';
import { buttonClass, FieldError, inputClass } from '../components/ui.gts';
// The hero's code sample, shown as text: a plain file, so formatters leave its line breaks alone.
import SAMPLE from '../hero-sample.txt?raw';
// useHttp posts JSON to an API route: no visit, the page stays, and a 422 fills form.errors.
class Subscribe extends Component {
form = useHttp<{ email: string }, { message: string; subscribers: number }>({ email: '' });
submit = async (event: SubmitEvent): Promise<void> => {
event.preventDefault();
const result = await this.form.post('/api/subscribers');
// A success makes the sent value the new default, so clear the field by hand.
if (result) {
this.form.email = '';
}
};
<template>
<form
class='mt-10 flex flex-col gap-3 rounded-2xl bg-white p-5 shadow-sm ring-1 ring-stone-200 sm:flex-row sm:items-start'
novalidate
data-test-subscribe
{{on 'submit' this.submit}}
>
<div class='flex-1'>
<label class='mb-1 block text-sm font-medium' for='email'>Weekly digest of new ideas</label>
<input id='email' type='email' class={{inputClass}} placeholder='you@example.com' {{bind this.form 'email'}} />
<FieldError @field='email' @message={{this.form.errors.email}} />
{{#if this.form.recentlySuccessful}}
<p class='mt-1 text-sm text-emerald-700' data-test-subscribed>{{this.form.response.message}}
{{this.form.response.subscribers}}
on the list.</p>
{{/if}}
</div>
<button type='submit' class='{{buttonClass}} sm:mt-6' disabled={{this.form.processing}}>
{{if this.form.processing 'Subscribing…' 'Subscribe'}}
</button>
</form>
</template>
}
const FEATURES = [
{
title: 'Infinite scroll and filters',
href: '/ideas',
body: 'The list loads 12 ideas at a time as you scroll. Search and category chips change the query with partial reloads, and the grid or list choice survives the back button.',
uses: ['<InfiniteScroll>', 'router.get', 'useRemember', '<Link @only>'],
},
{
title: 'Deferred and lazy props',
href: '/ideas/1',
body: 'An idea renders at once. Similar ideas arrive a moment later, and comments load only when you scroll down to them.',
uses: ['<Deferred>', '<WhenVisible>', 'inertia::defer', 'inertia::optional'],
},
{
title: 'Forms and validation',
href: '/ideas/new',
body: 'Each field is checked against Laravel Rust’s rules as you leave it, and similar titles show up as you type. A good idea redirects with a toast.',
uses: ['<Form>', 'useForm', '{{bind}}', 'Precognition', 'useHttp', 'flash'],
},
{
title: 'Polling',
href: '/dashboard',
body: 'The numbers refresh every two seconds with a partial reload that only asks for stats. The tab title follows the votes.',
uses: ['usePoll', '<Head>', 'inertia::lazy'],
},
];
export default <template>
<section class='mb-14 grid gap-10 lg:grid-cols-[1.2fr_1fr] lg:items-center'>
<div>
<p
class='mb-3 inline-flex items-center gap-2 rounded-full bg-white px-3 py-1 text-xs font-medium text-stone-600 shadow-sm ring-1 ring-stone-200'
>
<span class='size-1.5 rounded-full bg-[#e04e39]'></span>
The Ember adapter for Inertia v3
</p>
<h1 class='text-4xl font-semibold tracking-tight text-balance sm:text-5xl'>
Ember pages,
<span class='font-serif font-normal text-[#e04e39] italic'>server-side</span>
routing.
</h1>
<p class='mt-4 max-w-xl text-lg text-stone-600'>
This demo runs on Laravel Rust. Each handler returns a page name and its props, and inertia-ember renders a
<code class='rounded bg-stone-100 px-1 text-base'>.gts</code>
component with them. No API, no client router, no store.
</p>
<div class='mt-6 flex flex-wrap gap-3'>
<Link
@href='/ideas'
@prefetch='mount'
class='inline-flex items-center gap-2 rounded-lg bg-stone-900 px-4 py-2.5 text-sm font-medium text-white shadow-sm hover:bg-stone-700'
>Browse {{@props.ideas}} ideas →</Link>
<Link
@href='/ideas/new'
class='inline-flex items-center gap-2 rounded-lg border border-stone-300 bg-white px-4 py-2.5 text-sm font-medium shadow-sm hover:bg-stone-50'
>Post one</Link>
</div>
</div>
<figure class='overflow-hidden rounded-2xl bg-stone-900 text-sm text-stone-100 shadow-xl'>
<figcaption class='border-b border-white/10 px-4 py-2 font-mono text-xs text-stone-400'>
resources/js/pages/Ideas/Show.gts
</figcaption>
<pre class='overflow-x-auto p-4 font-mono text-[13px] leading-relaxed'><code>{{SAMPLE}}</code></pre>
</figure>
</section>
<section>
<h2 class='mb-4 text-sm font-semibold tracking-wider text-stone-500 uppercase'>Try each feature</h2>
<div class='grid gap-4 sm:grid-cols-2'>
{{#each FEATURES as |feature|}}
<Link
@href={{feature.href}}
@prefetch={{true}}
class='group rounded-2xl bg-white p-5 shadow-sm ring-1 ring-stone-200 transition hover:-translate-y-0.5 hover:shadow-md'
>
<h3 class='flex items-center justify-between font-semibold'>
{{feature.title}}
<span class='text-stone-400 transition group-hover:translate-x-1 group-hover:text-stone-900'>→</span>
</h3>
<p class='mt-2 text-sm text-stone-600'>{{feature.body}}</p>
<ul class='mt-4 flex flex-wrap gap-1.5'>
{{#each feature.uses as |use|}}
<li class='rounded-md bg-stone-100 px-1.5 py-0.5 font-mono text-xs text-stone-700'>{{use}}</li>
{{/each}}
</ul>
</Link>
{{/each}}
</div>
</section>
<Subscribe />
<p class='mt-10 text-sm text-stone-500'>
{{@props.ideas}}
ideas and
{{@props.comments}}
comments in this SQLite database. The layout above stays mounted while you move between pages; its clock proves it.
</p>
</template> satisfies TOC<PageSignature<{ ideas: number; comments: number }>>;The handler
rs
use laravel::inertia::{self, Page, props};
use crate::models::{Comment, Idea};
pub async fn show() -> laravel::Result<Page> {
let ideas = Idea::query().count().await?;
let comments = Comment::query().count().await?;
Ok(inertia::render("Welcome", props! { ideas, comments }))
}The newsletter endpoint is a JSON API route:
rs
//! JSON endpoints the pages call with `useHttp`, outside of Inertia visits.
use laravel::model::create;
use laravel::prelude::*;
use serde::Serialize;
use serde_json::{Value, json};
use crate::models::{Idea, Subscriber};
#[laravel::query]
pub struct SimilarQuery {
#[validate(max_length(120))]
title: Option<String>,
}
#[derive(Serialize)]
pub struct Match {
id: i64,
title: String,
votes: i64,
}
/// Ideas whose title shares a word with the one being typed, so the author can vote instead of repeating it.
pub async fn similar(Query(query): Query<SimilarQuery>) -> laravel::Result<Json<Vec<Match>>> {
let words: Vec<String> = query
.title
.unwrap_or_default()
.split_whitespace()
.filter(|word| word.chars().count() >= 4)
.map(str::to_lowercase)
.take(6)
.collect();
if words.is_empty() {
return Ok(Json(Vec::new()));
}
let mut ideas = Vec::new();
for word in &words {
for idea in Idea::query()
.filter(Idea::title.contains(word))
.order_by(Idea::votes.desc())
.limit(5)
.get()
.await?
{
if !ideas.iter().any(|known: &Match| known.id == idea.id) {
ideas.push(Match {
id: idea.id,
title: idea.title,
votes: idea.votes,
});
}
}
}
ideas.sort_by_key(|idea| std::cmp::Reverse(idea.votes));
ideas.truncate(5);
Ok(Json(ideas))
}
#[laravel::input]
#[validate(anyone)]
pub struct Subscribe {
#[transform(lowercase)]
#[validate(required, email, max_length(255), unique(Subscriber::email))]
email: String,
}
pub async fn subscribe(Valid(input): Valid<Subscribe>) -> laravel::Result<Json<Value>> {
let subscriber = create!(Subscriber { email: input.email }).await?;
let count = Subscriber::query().count().await?;
Ok(Json(json!({
"message": format!("Subscribed {}.", subscriber.email),
"subscribers": count,
})))
}