Query notes with typed columns

Declare a Note model, filter it with & and |, and count two tables at once with task::try_join!.

A model is a struct with #[model]. Each field is a column, except relationship fields, which come in the next lesson. The macro derives Clone, Debug, and Serialize. It also generates query, find, create, update, and delete, so a column cannot use those names. Table names default to the plural snake case of the struct: Note becomes notes.

src/models/note.rs:

use laravel::model::model;
use laravel::time::Timestamp;

#[model]
pub struct Note {
    pub id: i64,
    pub user_id: i64,
    pub title: String,
    pub body: String,
    pub created_at: Timestamp,
    pub updated_at: Timestamp,
}

Declare the module the same way user is declared in src/models/mod.rs, and re-export Note if other modules need it. An i64 id is assigned by the database, which matches table.id().

Filters the compiler can reject

Note::title and Note::user_id are typed columns. Comparing one to the wrong Rust type fails the build. Combine conditions with &, |, and ! instead of nested closures:

let notes = Note::query()
    .filter(Note::user_id.eq(user_id) & Note::title.starts_with("Field"))
    .latest(Note::created_at)
    .limit(20)
    .get()
    .await?;

eq, ne, lt, gt, is_in, and is_null are on the column. String columns also accept &str. Model queries select every column, because hydrating a model needs them. There is no select on the model query. A report that wants fewer columns uses db::table or db::query!, which the database guide describes. This lesson stays on the model.

Replace the placeholder index:

pub async fn index() -> laravel::Result<String> {
    let notes = Note::query().latest(Note::created_at).limit(20).get().await?;
    let lines: Vec<String> = notes.iter().map(|note| note.title.clone()).collect();
    Ok(lines.join("\n"))
}

An empty table returns an empty body. That is a successful query, not a 404.

Create one row without a form

Forms arrive in the next course. Until then, create! inserts a row and returns the stored model, including the generated id and timestamps. The models guide shows a belongs-to field accepting &user. You do not have that field yet, so set user_id directly with an id you know exists:

use laravel::model::create;

let note = create!(Note {
    user_id: user_id,
    title: "Read the migration",
    body: "The table is in the binary.",
}).await?;

Delete this temporary route once the validated form exists. A client must not be able to post user_id later. The fill struct in the access course is what prevents that.

Two counts without waiting twice

The tasks guide says to prefer laravel::task over tokio::spawn, because the helpers carry the application context and the tracing span. task::try_join! runs the futures together and returns them in order, or stops on the first error. Pass the futures without .await:

use laravel::db;
use laravel::task;

let (notes, users) = task::try_join!(
    db::table("notes").count(),
    db::table("users").count(),
)?;

They share one thread and interleave while waiting on I/O. Blocking work does not belong here. The same guide tells you to move that to task::spawn_blocking. task::background is for work that should outlive the response but still be waited on during shutdown. It is not a queue. The queue lesson is the one that survives a restart.

Check your work

Write a filter that compares a column to the wrong type and confirm the build fails before any SQL runs.

Back to roadmap