Course › Week 6 · Laravel Rust › Day 3 · lesson 38 of 42 · 30 min reading + 45 min practice
Models and migrations
A #[model] on an existing table, typed queries the compiler checks, relationships and migrations in Rust.
On this page
Eloquent in Laravel Rust is a struct with #[model] on it. Each field is a column, with the column’s type, so the compiler knows the shape of every row. A query that compares a column with the wrong kind of value, or reads a relationship that was not loaded, is caught before it runs, not when a user opens the page.
This lesson gives the nordic application the Week 4 tables, evaluations and answers, as migrations and models, and stores the batch that the routes and input lesson only validated.
1. A migration
laravel make:migration writes a migration file named after the current time, as php artisan make:migration does. The name decides the start: create_evaluations_table gives a create("evaluations", …) with an id and timestamps.
The migration is a Rust function. tx.schema().create(…) takes the table’s name and a closure that adds the columns, with Laravel’s method names: id(), string, integer, timestamps(), and modifiers such as .nullable() and .default(…).
Migration created at `database/migrations/2026_12_02_013407_create_evaluations_table.rs`.The file it wrote has only the id and the timestamps. With the columns of the Week 4 table filled in, renamed to a fixed date so that every page of this course shows the same name (yours carries the time you ran the command):
use laravel::db::AnyTransaction;
pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
tx.schema()
.create("evaluations", |table| {
table.id();
table.string("school");
table.string("status").length(20).default("pending");
table.integer("average_tenths").nullable();
table.timestamps();
})
.await
}
Migrating `0001_01_01_000000_create_users_table`...
Migrating `0001_01_01_000001_create_cache_table`...
Migrating `0001_01_01_000002_create_jobs_table`...
Migrating `2026_12_07_000000_create_evaluations_table`...
4 migrations ran.The migration runs inside a transaction (AnyTransaction) together with its line in the migrations table, so on Postgres a migration that fails leaves nothing half-done.
There is no down(). Migrations only go forward: to undo a change in a live application you write a new migration that reverses it. Once a migration has run on a shared database, never edit it, because an edited migration does not run again. The answers table therefore gets a migration of its own in section 6, not a few more lines in this one.
2. A model
#[model] turns a struct into a model of the table named after it in snake case, plural: Evaluation reads and writes evaluations. Every column is a field with its Rust type, and a nullable column is an Option, so average_tenths is None until the analysis fills it.
status is an enum column: the Enum derive stores each variant as its serde name, "pending" or "analysed", like a PHP backed enum cast. #[default] says the database has a default for it, so creating an evaluation may leave it out.
use laravel::model::model;
use laravel::prelude::*;
use laravel::time::Timestamp;
use serde::{Deserialize, Serialize};
/// Where an evaluation is in the analysis.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, Enum)]
#[serde(rename_all = "snake_case")]
pub enum Status {
Pending,
Analysed,
}
#[model]
pub struct Evaluation {
pub id: i64,
pub school: String,
#[default]
pub status: Status,
pub average_tenths: Option<i32>,
pub created_at: Timestamp,
pub updated_at: Timestamp,
}
Each model is a module of src/models, re-exported from its mod.rs, so handlers write use crate::models::Evaluation:
mod evaluation;mod user; pub use evaluation::{Evaluation, Status};pub use user::{User, UserFactory};
#[model] also derives Clone, Debug and Serialize, and gives the struct its query functions: find, query, all and the rest. That is why a field cannot be called query.
3. Creating rows
create!(Evaluation { school: "Alexandria STEM" }) inserts a row and returns the stored model, with its new id, its timestamps and the database default for status. The fields left out get their default or NULL. It is Evaluation::create([...]), checked: a field that is not a column, or a value of the wrong type, does not compile.
Sample rows go in the seeder, as in PHP. laravel migrate --seed runs the migrations, then the default seeder:
use laravel::db::seeder;use laravel::model::create; use crate::models::User;use crate::models::{Evaluation, User}; #[seeder(default, without_events)]pub async fn database() -> laravel::Result<()> { // User::factory().count(10).create().await?; create!(User::factory() { name: "Test User", email: "test@example.com", }) .await?; create!(Evaluation { school: "Alexandria STEM" }) .await?; create!(Evaluation { school: "Cairo Language School" }) .await?; Ok(())}
Migrating `0001_01_01_000000_create_users_table`...
Migrating `0001_01_01_000001_create_cache_table`...
Migrating `0001_01_01_000002_create_jobs_table`...
Migrating `2026_12_07_000000_create_evaluations_table`...
4 migrations ran.
database 613.9ms
Database seeded.4. Route model binding
A handler that takes an Evaluation gets the one the URI names. Laravel matches the {evaluation} parameter by name, the model’s name in snake case, and loads it by its key. No row with that id, or an id that is not a number, and the request is a 404 before the handler runs. It is show(Evaluation $evaluation), as in PHP.
use laravel::prelude::*;use serde::{Deserialize, Serialize}; use crate::models::Evaluation; /// The formats an evaluation can be exported in. Any other value in the URI is a 404.#[derive(Clone, Copy, Deserialize, Serialize)]#[serde(rename_all = "lowercase")]20 unchanged lines
pub enum Format { Csv, Xlsx,} #[derive(Serialize)]pub struct Export { evaluation: i64, format: Format, url: String,} pub async fn export(Params((id, format)): Params<(i64, Format)>) -> Json<Export> { let extension = match format { Format::Csv => "csv", Format::Xlsx => "xlsx", }; Json(Export { evaluation: id, format, url: format!("/exports/evaluation-{id}.{extension}"), })} /// One evaluation, found by the {evaluation} in the URI. An unknown id is a 404 before this runs.pub async fn show(evaluation: Evaluation) -> Json<Evaluation> { Json(evaluation)}
18 unchanged lines
use laravel::prelude::*;use serde::Serialize;use serde_json::json; use crate::http::handlers::{batches, evaluations}; /// What /api/status reports, for Laravel's health checks and for people.#[derive(Serialize)]struct Status { service: &'static str, laravel: &'static str,} pub fn routes(route: &mut Router) { route.get("/version", async || Json(json!({ "laravel": laravel::VERSION }))); route.get("/status", async || { Json(Status { service: "nordic", laravel: laravel::VERSION, }) }); route.get("/evaluations/{evaluation}", evaluations::show); route.get("/evaluations/{evaluation}/export/{format}", evaluations::export); route.post("/batches", batches::store); route.fallback(async || laravel::abort(404));}
HTTP/1.1 200 OK
content-type: application/json
content-length: 162
vary: access-control-request-method, access-control-request-headers
access-control-allow-origin: *
x-frame-options: SAMEORIGIN
x-content-type-options: nosniff
x-request-id: d0f48c64ef34e3c0c4d052be15275cb1
{"id":1,"school":"Alexandria STEM","status":"pending","average_tenths":null,"created_at":"2026-12-02T01:34:36.892125Z","updated_at":"2026-12-02T01:34:36.892125Z"}HTTP/1.1 404 Not Found
content-type: application/json
content-length: 23
vary: access-control-request-method, access-control-request-headers
access-control-allow-origin: *
x-frame-options: SAMEORIGIN
x-content-type-options: nosniff
x-request-id: 24dbfd7be976e26a3b0adbdd84c90c95
{"message":"Not Found"}HTTP/1.1 404 Not Found
content-type: application/json
content-length: 23
vary: access-control-request-method, access-control-request-headers
access-control-allow-origin: *
x-frame-options: SAMEORIGIN
x-content-type-options: nosniff
x-request-id: 73ede8e514510a555af1231d3366338c
{"message":"Not Found"}Server running at `http://127.0.0.1:3000`. Press Ctrl+C to stop.
GET 200 /api/evaluations/1 7.6ms
GET 404 /api/evaluations/99 2.3ms
GET 404 /api/evaluations/abc 0.9msJson(evaluation) is the whole model, because #[model] derived Serialize: the enum as its name, timestamps in ISO 8601 UTC. A column that must never leave the server, like the password of the skeleton’s User, gets #[serde(skip)].
5. Queries the compiler checks
Evaluation::query() starts a query on the table; filter, order_by and get build and run it. Evaluation::status is not a string with a column name in it: #[model] generated a typed column for every field, so Evaluation::status.eq(…) accepts only a Status.
Writing .eq("pending") instead does not compile: the error reads “a Status column can’t be compared with &str”. In Eloquent, where('stauts', 'pending') with a typo in the column runs and fails in production; here a wrong column name or a wrong type stops the build.
use laravel::prelude::*;use serde::{Deserialize, Serialize}; use crate::models::Evaluation;use crate::models::{Evaluation, Status}; /// The formats an evaluation can be exported in. Any other value in the URI is a 404.#[derive(Clone, Copy, Deserialize, Serialize)]26 unchanged lines
#[serde(rename_all = "lowercase")]pub enum Format { Csv, Xlsx,} #[derive(Serialize)]pub struct Export { evaluation: i64, format: Format, url: String,} pub async fn export(Params((id, format)): Params<(i64, Format)>) -> Json<Export> { let extension = match format { Format::Csv => "csv", Format::Xlsx => "xlsx", }; Json(Export { evaluation: id, format, url: format!("/exports/evaluation-{id}.{extension}"), })} /// One evaluation, found by the {evaluation} in the URI. An unknown id is a 404 before this runs.pub async fn show(evaluation: Evaluation) -> Json<Evaluation> { Json(evaluation)} /// Every evaluation still waiting for the analysis, oldest first.pub async fn pending() -> laravel::Result<Json<Vec<Evaluation>>> { let evaluations = Evaluation::query() .filter(Evaluation::status.eq(Status::Pending)) .order_by(Evaluation::id) .get() .await?; Ok(Json(evaluations))}
18 unchanged lines
use laravel::prelude::*;use serde::Serialize;use serde_json::json; use crate::http::handlers::{batches, evaluations}; /// What /api/status reports, for Laravel's health checks and for people.#[derive(Serialize)]struct Status { service: &'static str, laravel: &'static str,} pub fn routes(route: &mut Router) { route.get("/version", async || Json(json!({ "laravel": laravel::VERSION }))); route.get("/status", async || { Json(Status { service: "nordic", laravel: laravel::VERSION, }) }); route.get("/evaluations/pending", evaluations::pending); route.get("/evaluations/{evaluation}", evaluations::show); route.get("/evaluations/{evaluation}/export/{format}", evaluations::export); route.post("/batches", batches::store); route.fallback(async || laravel::abort(404));}
HTTP/1.1 200 OK
content-type: application/json
content-length: 333
vary: access-control-request-method, access-control-request-headers
access-control-allow-origin: *
x-frame-options: SAMEORIGIN
x-content-type-options: nosniff
x-request-id: be6e9d3ba852e9cd8593a5313b3a3184
[{"id":1,"school":"Alexandria STEM","status":"pending","average_tenths":null,"created_at":"2026-12-02T01:34:47.984837Z","updated_at":"2026-12-02T01:34:47.984837Z"},{"id":2,"school":"Cairo Language School","status":"pending","average_tenths":null,"created_at":"2026-12-02T01:34:47.986222Z","updated_at":"2026-12-02T01:34:47.986222Z"}]Server running at `http://127.0.0.1:3000`. Press Ctrl+C to stop.
GET 200 /api/evaluations/pending 7.5ms
Stopping. Waiting up to 20s for the work in progress./evaluations/pending is registered before /evaluations/{evaluation}, but its order does not matter: a fixed segment such as pending beats a parameter whichever comes first. The handler returns laravel::Result<…> because a query can fail; ? passes a database error up, and Laravel answers it with a 500 that logs the cause, like the errors lesson’s AppError.
6. A relationship, loaded up front
The answers table gets its own migration. foreign_id("evaluation_id").constrained() is the same foreign key as in PHP:
use laravel::db::AnyTransaction;
pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
tx.schema()
.create("answers", |table| {
table.id();
table.foreign_id("evaluation_id").constrained();
table.string("question").length(20);
table.small_integer("score");
table.text("comment").nullable();
table.timestamps();
})
.await
}
An Answer model with #[belongs_to], and on Evaluation a #[has_many] field. A relationship field is not a column; it holds the related rows once they are loaded.
use laravel::model::{BelongsTo, model};
use laravel::time::Timestamp;
use crate::models::Evaluation;
#[model]
pub struct Answer {
pub id: i64,
pub evaluation_id: i64,
pub question: String,
pub score: i16,
pub comment: Option<String>,
pub created_at: Timestamp,
pub updated_at: Timestamp,
#[belongs_to]
pub evaluation: BelongsTo<Evaluation>,
}
use laravel::model::model;use laravel::model::{HasMany, model};use laravel::prelude::*;use laravel::time::Timestamp;use serde::{Deserialize, Serialize}; use crate::models::Answer; /// Where an evaluation is in the analysis.#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, Enum)]#[serde(rename_all = "snake_case")]11 unchanged lines
pub enum Status { Pending, Analysed,} #[model]pub struct Evaluation { pub id: i64, pub school: String, #[default] pub status: Status, pub average_tenths: Option<i32>, pub created_at: Timestamp, pub updated_at: Timestamp, #[has_many] pub answers: HasMany<Answer>,}
mod answer;mod evaluation;mod user; pub use answer::Answer;pub use evaluation::{Evaluation, Status};pub use user::{User, UserFactory};
The seeder gives the first evaluation two answers. evaluation: &stem sets evaluation_id from the model:
use laravel::db::seeder;use laravel::model::create; use crate::models::{Evaluation, User};use crate::models::{Answer, Evaluation, User}; #[seeder(default, without_events)]pub async fn database() -> laravel::Result<()> { create!(User::factory() { name: "Test User", email: "test@example.com", }) .await?; create!(Evaluation { let stem = create!(Evaluation { school: "Alexandria STEM" }) .await?; create!(Answer { evaluation: &stem, question: "Q1", score: 5_i16, comment: "Clear explanations" }) .await?; create!(Answer { evaluation: &stem, question: "Q2", score: 4_i16 }) .await?; create!(Evaluation { school: "Cairo Language School" }) .await?; Ok(())}
Relationships are never lazy-loaded. There is no $evaluation->answers that quietly runs a query; you ask for them with with(Evaluation::answers), and Laravel runs the evaluations query, then one query for the answers of all of them. The N+1 problem that preventLazyLoading() warns about in PHP cannot happen.
43 unchanged lines
use laravel::prelude::*;use serde::{Deserialize, Serialize}; use crate::models::{Evaluation, Status}; /// The formats an evaluation can be exported in. Any other value in the URI is a 404.#[derive(Clone, Copy, Deserialize, Serialize)]#[serde(rename_all = "lowercase")]pub enum Format { Csv, Xlsx,} #[derive(Serialize)]pub struct Export { evaluation: i64, format: Format, url: String,} pub async fn export(Params((id, format)): Params<(i64, Format)>) -> Json<Export> { let extension = match format { Format::Csv => "csv", Format::Xlsx => "xlsx", }; Json(Export { evaluation: id, format, url: format!("/exports/evaluation-{id}.{extension}"), })} /// One evaluation, found by the {evaluation} in the URI. An unknown id is a 404 before this runs.pub async fn show(evaluation: Evaluation) -> Json<Evaluation> { Json(evaluation)} /// Every evaluation still waiting for the analysis, oldest first.pub async fn pending() -> laravel::Result<Json<Vec<Evaluation>>> { let evaluations = Evaluation::query() .filter(Evaluation::status.eq(Status::Pending)) .order_by(Evaluation::id) .get() .await?; Ok(Json(evaluations))} /// One evaluation with its answers, in two queries whatever the number of answers.pub async fn with_answers(Params(id): Params<i64>) -> laravel::Result<Json<Evaluation>> { let evaluation = Evaluation::query().with(Evaluation::answers).find_or_fail(id).await?; Ok(Json(evaluation))}
20 unchanged lines
use laravel::prelude::*;use serde::Serialize;use serde_json::json; use crate::http::handlers::{batches, evaluations}; /// What /api/status reports, for Laravel's health checks and for people.#[derive(Serialize)]struct Status { service: &'static str, laravel: &'static str,} pub fn routes(route: &mut Router) { route.get("/version", async || Json(json!({ "laravel": laravel::VERSION }))); route.get("/status", async || { Json(Status { service: "nordic", laravel: laravel::VERSION, }) }); route.get("/evaluations/pending", evaluations::pending); route.get("/evaluations/{evaluation}", evaluations::show); route.get("/evaluations/{evaluation}/answers", evaluations::with_answers); route.get("/evaluations/{evaluation}/export/{format}", evaluations::export); route.post("/batches", batches::store); route.fallback(async || laravel::abort(404));}
HTTP/1.1 200 OK
content-type: application/json
content-length: 498
vary: access-control-request-method, access-control-request-headers
access-control-allow-origin: *
x-frame-options: SAMEORIGIN
x-content-type-options: nosniff
x-request-id: 42394090e251a45bbea170f801266a07
{"id":1,"school":"Alexandria STEM","status":"pending","average_tenths":null,"created_at":"2026-12-02T01:35:29.706822Z","updated_at":"2026-12-02T01:35:29.706822Z","answers":[{"id":1,"evaluation_id":1,"question":"Q1","score":5,"comment":"Clear explanations","created_at":"2026-12-02T01:35:29.708287Z","updated_at":"2026-12-02T01:35:29.708287Z"},{"id":2,"evaluation_id":1,"question":"Q2","score":4,"comment":null,"created_at":"2026-12-02T01:35:29.710044Z","updated_at":"2026-12-02T01:35:29.710044Z"}]}HTTP/1.1 200 OK
content-type: application/json
content-length: 162
vary: access-control-request-method, access-control-request-headers
access-control-allow-origin: *
x-frame-options: SAMEORIGIN
x-content-type-options: nosniff
x-request-id: 05a1f74a73498b3bf3ecb8867543f6a2
{"id":1,"school":"Alexandria STEM","status":"pending","average_tenths":null,"created_at":"2026-12-02T01:35:29.706822Z","updated_at":"2026-12-02T01:35:29.706822Z"}Server running at `http://127.0.0.1:3000`. Press Ctrl+C to stop.
GET 200 /api/evaluations/1/answers 9.3ms
GET 200 /api/evaluations/1 1.9ms
Stopping. Waiting up to 20s for the work in progress.The first response has answers, the second does not: a relationship that was not loaded is left out of the JSON. Reading it in Rust, evaluation.answers.len() without with, panics with a message naming the missing with(Evaluation::answers), so the mistake shows at the first test, not as a slow page.
7. The batch, stored
The batch’s table, with a unique reference and the evaluation ids as JSON:
use laravel::db::AnyTransaction;
pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
tx.schema()
.create("analysis_batches", |table| {
table.id();
table.string("reference").length(100).unique();
table.string("status").length(20).default("queued");
table.jsonb("evaluation_ids");
table.timestamps();
})
.await
}
Json<Vec<i64>> is the model’s type for a JSON column holding a list, the array cast of PHP. BatchStatus is the same kind of enum column as Status.
use laravel::db::Json;
use laravel::model::model;
use laravel::prelude::*;
use laravel::time::Timestamp;
use serde::{Deserialize, Serialize};
/// Where a batch is: queued until a worker takes it, then done or failed.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, Enum)]
#[serde(rename_all = "snake_case")]
pub enum BatchStatus {
Queued,
Running,
Done,
Failed,
}
#[model]
pub struct AnalysisBatch {
pub id: i64,
pub reference: String,
#[default]
pub status: BatchStatus,
pub evaluation_ids: Json<Vec<i64>>,
pub created_at: Timestamp,
pub updated_at: Timestamp,
}
mod analysis_batch;mod answer;mod evaluation;mod user; pub use analysis_batch::{AnalysisBatch, BatchStatus};pub use answer::Answer;pub use evaluation::{Evaluation, Status};pub use user::{User, UserFactory};
store now creates the batch. unique(AnalysisBatch::reference) is the unique:analysis_batches,reference rule, with a typed column instead of a string. laravel::db::Json is imported as JsonColumn because the prelude’s Json is the response type, and one module cannot use one name for two things.
use laravel::db::Json as JsonColumn;use laravel::model::create;use laravel::prelude::*;use serde::Serialize; use crate::models::AnalysisBatch; /// A batch of evaluations to analyse, as Laravel posts it.#[laravel::input]#[validate(anyone)]pub struct NewBatch { #[validate(required, max_length(100))] #[validate(required, max_length(100), unique(AnalysisBatch::reference))] reference: String, #[validate(required, max_items(500), distinct, each(min_value(1)))] evaluation_ids: Vec<i64>,} #[derive(Serialize)]pub struct Accepted { reference: String, evaluations: usize,} pub async fn store(Valid(batch): Valid<NewBatch>) -> (StatusCode, Json<Accepted>) { let accepted = Accepted { evaluations: batch.evaluation_ids.len(),/// Stores the batch as queued. The queue lesson gives it to a worker.pub async fn store(Valid(batch): Valid<NewBatch>) -> laravel::Result<(StatusCode, Json<AnalysisBatch>)> { let evaluation_ids = JsonColumn(batch.evaluation_ids); let stored = create!(AnalysisBatch { reference: batch.reference, }; (StatusCode::ACCEPTED, Json(accepted)) evaluation_ids }) .await?; Ok((StatusCode::ACCEPTED, Json(stored)))}
HTTP/1.1 202 Accepted
content-type: application/json
content-length: 164
vary: access-control-request-method, access-control-request-headers
access-control-allow-origin: *
x-frame-options: SAMEORIGIN
x-content-type-options: nosniff
x-request-id: 2805a92d48b296e79659f0495c486003
{"id":1,"reference":"dashboard-7f3e","status":"queued","evaluation_ids":[1,2],"created_at":"2026-12-02T01:35:54.990828Z","updated_at":"2026-12-02T01:35:54.990828Z"}HTTP/1.1 422 Unprocessable Entity
content-type: application/json
content-length: 116
vary: access-control-request-method, access-control-request-headers
access-control-allow-origin: *
x-frame-options: SAMEORIGIN
x-content-type-options: nosniff
x-request-id: 64b7586f55e9ef0d61bd3512e567af8f
{"message":"The reference has already been taken.","errors":{"reference":["The reference has already been taken."]}}Server running at `http://127.0.0.1:3000`. Press Ctrl+C to stop.
POST 202 /api/batches 10.0ms
POST 422 /api/batches 2.9ms
Stopping. Waiting up to 20s for the work in progress.The second post is a 422: the rule found the reference taken. The rule checks, then the insert runs, so two requests at the same moment could both pass the check; the unique index in the migration is what stops the second one. The Week 5 service answered a repeated reference with the same batch, so that a retried request is safe; the build day of this week brings that back.
The same model in Eloquent
<?php
namespace App\Models;
use App\Enums\EvaluationStatus;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Evaluation extends Model
{
protected $fillable = ['school'];
protected function casts(): array
{
return ['status' => EvaluationStatus::class];
}
public function answers(): HasMany
{
return $this->hasMany(Answer::class);
}
}
The Eloquent model lists none of its columns: they come from the database at runtime, and $evaluation->schol is null without a word. The Laravel Rust model lists every column with its type, so the same typo is a compile error, and the JSON a handler sends is the struct, field for field. The price is keeping the struct in step with the migrations, which in PHP the database does for you.
PracticeThe models, relationships and migrations guides
Read models up to “Updating models”, the “Eager loading” part of relationships, and migrations. The same files are in the crate’s docs/ folder.
Exercise: the answers of a school
Add GET /api/schools/{school}/answers: every answer of every evaluation of that school, in two queries. Load the evaluations with filter(Evaluation::school.eq(…)) and with(Evaluation::answers), and answer with the evaluations. Then try Evaluation::school.eq(42) and read the error.
Remember
- A model is a struct with
#[model]: every column a typed field, and typed columns in queries, so a wrong column or type does not compile. - Relationships are never lazy-loaded: ask with
with(…). Migrations only go forward.
Tomorrow: errors, middleware and the HTTP client. laravel::Result and abort, an API key check, and calling the analysis API with retries.