MARY.WIN

RUSTY — LARAVEL TO RUST — 13

Eloquent brain versus
Rust data modeling

Put a small invariant in a type and keep persistence as a separate decision.
Tutorial 13 of 16 in From Laravel to Rust. Before you start: Enums, Result, and ownership.

Which task states can the program represent, and which transitions can it reject? In examples/src/bin/ep13.rs, the Status enum represents Pending, Running, and Finished. Methods on Task enforce the order of local transitions. The example performs no database operation.

Task stores an ID, title, and status. Task::new() validates the title. Task::start() and Task::finish() check the current status before changing it. Persistence would require an additional storage operation outside these methods.

Before running the source, predict finish() on a pending task. Then predict a second call to start() after the first call succeeds. Compare those predictions with the rejected transitions in main().

This lesson covers putting a rule in a type: a Status enum whose Finished variant carries its output, a TaskId newtype, a constructor that validates the title, and transition methods that return specific errors. It keeps persistence as a separate decision. It leaves out ORMs, SQL, and serialization. It assumes Tutorials 2, 6, and 7. The Laravel reference point is Eloquent, whose Active Record approach combines record representation with persistence behavior. The example here performs no database operation; persistence would take an additional storage operation outside the methods you are about to read.

Take a look at Example 1.

Example 1. Complete example (examples/src/bin/ep13.rs)

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct TaskId(u64);

#[derive(Debug, PartialEq)]
enum Status { Pending, Running, Finished { output: String } }

#[derive(Debug, PartialEq)]
enum TransitionError { NotPending, NotRunning }

struct Task { id: TaskId, title: String, status: Status }

impl Task {
    fn new(id: TaskId, title: String) -> Result<Self, &'static str> {
        let title = title.trim().to_owned();
        if title.is_empty() { return Err("empty title"); }
        Ok(Self { id, title, status: Status::Pending })
    }

    fn start(&mut self) -> Result<(), TransitionError> {
        if self.status != Status::Pending {
            return Err(TransitionError::NotPending);
        }
        self.status = Status::Running;
        Ok(())
    }

    fn finish(&mut self, output: String) -> Result<(), TransitionError> {
        if self.status != Status::Running {
            return Err(TransitionError::NotRunning);
        }
        self.status = Status::Finished { output };
        Ok(())
    }
}

fn main() {
    let mut task = Task::new(TaskId(7), " tests ".into()).unwrap();
    assert_eq!(task.id, TaskId(7));
    assert_eq!(task.title, "tests");
    assert_eq!(task.finish("early".into()), Err(TransitionError::NotRunning));
    assert_eq!(task.start(), Ok(()));
    assert_eq!(task.start(), Err(TransitionError::NotPending));
    assert_eq!(task.finish("passed".into()), Ok(()));
    assert_eq!(task.status, Status::Finished { output: "passed".into() });
    assert!(Task::new(TaskId(8), " ".into()).is_err());
    println!("the allowed transitions are explicit");
}

Before you run it, predict what finish() returns on a pending task, and what a second call to start() returns after the first one succeeds. Then compare your predictions with the assertions in main().

Expected output:

TERMINAL
cargo run --quiet --bin ep13
the allowed transitions are explicit

The call that came too early

The call task.finish("early".into()) held that a task could be finished as soon as someone had an output for it. It sat on the fourth line of main, before anything had called start, and it carried the string "early". finish checked the status, found Status::Pending, and returned Err(TransitionError::NotRunning). The status stayed Pending.

Sometimes a record can be saved in a state the product forbids, and the only thing preventing it is that every writer remembers the rule. Thankfully, some rules fit in the type. Take another look at Example 1.

There are four pieces. Status is an enum, and Finished contains its output; Pending and Running have no such field. TaskId wraps a u64. Task::new trims the title and returns Err("empty title") when nothing is left. And start and finish check the current status before changing it: start accepts only Status::Pending, and finish accepts only Status::Running.

Now follow the calls in main in order. Each row is one assertion, and every assertion passed before the program printed its line.

Call Status before Result
task.finish("early".into()) Pending Err(TransitionError::NotRunning)
task.start() Pending Ok(())
task.start() Running Err(TransitionError::NotPending)
task.finish("passed".into()) Running Ok(())

After the last row, task.status is Status::Finished { output: "passed".into() }. Drawn as states, the allowed sequence is Pending → Running → Finished, with start() on the first arrow and finish() on the second. Each refusal sits beside the arrow it blocks: NotRunning for a finish() that comes before start(), and NotPending for a second start().

What does the enum rule out?

Status::Finished { output: String } requires an output field, and Status::Pending and Status::Running have none, so the enum cannot represent a Finished variant with that field omitted. That is more useful than a slogan about making invalid states impossible, because it names the one combination removed. It does not show that the output is truthful, that the task really ran, or that another process cannot overwrite a database row.¹

Identity is a separate concept

TaskId wraps a number, which makes it a different type from another numeric identifier such as a UserId, so it can stop you passing one kind of identifier where the other belongs. It does not validate that the record exists, prove the current user may read it, or make the number globally unique. Those are distinct requirements, and the design should keep them distinct.

Validation is another boundary. Task::new trims the supplied title before storing it, and an empty trimmed title returns Err("empty title"). In main, " tests " becomes tests, and a separate assertion rejects a blank title. Mark Task::new as the input boundary and label it validation; persistence sits outside this example. Incoming JSON or database rows must pass through the same validation boundary.

Where Eloquent still helps

Eloquent's Active Record approach combines record representation with persistence behavior, and for many Laravel applications that combination is productive. I would not replace every Eloquent model with five layers of classes. Identify the rule that needs a stable home: a small value object, an enum, or a method can hold an invariant while the application still uses Eloquent for storage.

You can also arrange persistence differently in Rust. A mapper can translate rows into domain values. A query can return a read-specific projection. An application service can coordinate a transaction. A repository fits where there is a domain-oriented collection boundary or a real replacement need, and is not required around every SQL statement.

The race the type cannot settle

Imagine two workers load the same pending task. Each local value permits start, and each call returns Ok(()), and the type, which did exactly what it was built to do for the one value it could see, has no knowledge of the other worker or of the row both values came from, so that without a conditional update, a version check, a transaction with suitable locking, or some other storage-specific mechanism, both workers believe they claimed it.

A passing unit test for Task is evidence about the rule. A database-backed claim needs its own concurrency check.

So the transitions are explicit and the assertions pass. Now take one status column in your application. Which combinations with its neighboring columns are forbidden? Where is that written: in the schema, in a method, or in the habits of the people who write to it? What happens when two requests change it at once?

Testing

Start from memory. Without looking at the listing, write down the allowed sequence and its two refusals, and then check what you wrote against the table above.

Then extend the example. Add Status::Failed { reason: String } and a Task::fail() method that accepts only Running. Before you add any assertions, predict three calls: failure before start, failure while running, and finishing after failure. Write the predictions down.

Now compare. Failure before start should return a transition error. Failure while running should keep the reason in Failed. Finishing after failure should be rejected by the running-state check that finish already makes. Then decide, as a separate question, whether a retry creates a new task or resets this one, and keep historical attempts when an audit trail is a requirement.

TL;DR

The Task methods protect transitions on one local value. Status::Finished carries its output, so a finished task without one cannot be represented. start() accepts only Pending, finish() accepts only Running, and each refusal has a name. TaskId separates identifiers and proves nothing about existence or permission. Task::new is the validation boundary, and persistence is a separate decision. A database-backed claim needs its own concurrency check, because two pending values loaded separately can both pass start().

¹ In this single-file demonstration, module privacy is not a boundary against code in the same module. A real library should place the type in a module, keep its fields private, and expose only the constructors and operations it intends to support. Public fields would let callers bypass the methods.

The sources.

Every program, its output and every compiler message were recorded on rustc 1.100.0 on 2026-11-20. Each page lists what was not checked.

Rust Book, defining structs, enums, and module privacy; Laravel 13 Eloquent and database transactions; Martin Fowler's Active Record and Data Mapper catalog entries. The task state machine is an original example.

NOT CHECKED — 3
  • The outcomes given for the Failed exercise come from reading the code; the exercise code was not written or run.
  • Statements about Eloquent, Active Record, Data Mapper, repositories and database concurrency mechanisms are carried from the tutorial text and were not re-checked against the Laravel documentation or Martin Fowler's catalog for this edition.
  • The reference links were not opened for this edition.