Laravel in production
Sign in

Topics

Backend

Tools & DevOps

All guides

Search

Topics

Practice

Architecture · Laravel in production

From Laravel to Laravel Rust. Day 2: the first models and token login

Author: Volodymyr Pichkurov Published: 9 min read
Laravel Rust Laravel Rust APIs & integrations

On day one we moved the page view counter to Rust. Honestly, that was a warm-up: no login, no sessions, one insert into one table. Today we take on a more serious route. It has tokens, roles, restricted projects, three different rate limits and users who actually rely on it.

Meet POST /api/zones/{project}/check.


In short

  • What we move: the pre-commit check from the DevSense team space. A git hook asks the server: am I touching files that someone else is holding right now?
  • What is new since day one: the first Rust models on top of PHP tables, login with a personal token, three rate limits and team permission checks.
  • The result: 26 scenarios — from "no token" to "a path with a control character" — return the same status codes and the same bodies in PHP and Rust.
  • The honest mismatch: just one, and more on it below.

Test subject number two

In the DevSense team space, people and their AI agents "claim" folders and files so they do not edit the same thing at the same time. Before every commit, the pre-commit git hook sends the list of changed files and gets an answer:

json
{
  "clear": false,
  "strict": true,
  "conflicts": [
    { "path": "src/app", "who": "Maria", "agent": "claude", "until": "2026-12-04T23:45:00+00:00" }
  ]
}

If the project is strict, the commit stops. If not, the hook warns and lets it through.

Why this route is a good second step:

  • a token instead of a session — there is authentication, but no PHP cookies or sessions; we save those for day three;
  • real logic — team roles, restricted projects, projects a token is bound to;
  • real users — the hook fires on every commit, so a bug here will be noticed;
  • a clear fallback — the hook already survives a server outage: "could not check — commit allowed".

The first models: Rust looks into PHP tables

PHP created the tables, and the migrations belong to it. Rust only reads for now. So the Rust models have to mirror exactly what already sits in the database.

Here is a path claim in PHP:

php
class ZoneClaim extends Model
{
    protected $fillable = ['project_id', 'user_id', 'agent_label', 'path', 'note', 'expires_at', 'released_at'];

    protected function casts(): array
    {
        return ['expires_at' => 'datetime', 'released_at' => 'datetime'];
    }

    public function scopeActive(Builder $query): Builder
    {
        return $query->whereNull('released_at')->where('expires_at', '>', now());
    }
}

And here is the same claim in Laravel Rust:

rust
#[model]
pub struct ZoneClaim {
    pub id: i64,
    pub project_id: i64,
    pub user_id: i64,
    pub agent_label: Option<String>,
    pub path: String,
    pub note: Option<String>,
    pub expires_at: Timestamp,
    pub released_at: Option<Timestamp>,
    pub created_at: Option<Timestamp>,
    pub updated_at: Option<Timestamp>,
}

The difference in philosophy jumps out at once. A PHP model says what may be written and how to cast types, and picks up the columns from the database on the fly. A Rust model is the table row itself: every field, its type and whether it can be empty. Option<Timestamp> here is the same as nullable() in a migration.

From our first date with models we took away three rules:

  1. List every column. A Laravel Rust model query selects all of the model's fields, not *. Skip a column, and Rust simply will not see it. Make a typo in a name, and the query fails.
  2. Keep in sync with PHP migrations. The compiler checks types against the struct, not against the live database schema. So the rule is simple: a PHP migration changes a table — the Rust model changes in the same PR.
  3. Do not pull in extras. We did not describe the users table as a model: there is no reason to load a password hash into Rust for the sake of two flags. A targeted query was enough:
rust
/// The few columns of `users` this route needs (never the password or the e-mail).
#[derive(db::FromRow)]
struct Account {
    is_blocked: bool,
    email_verified_at: Option<Timestamp>,
}

And scopeActive turned into plain typed query conditions:

rust
let claims = ZoneClaim::query()
    .filter(ZoneClaim::project_id.eq(project.id))
    .filter(ZoneClaim::released_at.is_null())
    .filter(ZoneClaim::expires_at.gt(Timestamp::now()))
    .filter(ZoneClaim::user_id.ne(user_id))
    .order_by(ZoneClaim::id)
    .get()
    .await?;

Try comparing ZoneClaim::expires_at with a string — the code will not compile. In PHP, the same mistake would live all the way to production.


Token login: one middleware, three rate limits

In PHP, token login lives in the auth.pat middleware. Its heart is the token lookup:

php
public static function findValid(string $raw): ?self
{
    if (! str_starts_with($raw, self::PREFIX) && ! str_starts_with($raw, self::OAUTH_ACCESS_PREFIX)) {
        return null;
    }

    $token = self::query()
        ->where('token_hash', hash('sha256', $raw))
        ->whereNull('revoked_at')
        ->first();

    if ($token === null || $token->isExpired()) {
        return null;
    }

    return $token;
}

In Rust it is almost letter for letter:

rust
async fn find_valid(raw: &str) -> laravel::Result<Option<PortfolioToken>> {
    if !TOKEN_PREFIXES.iter().any(|p| raw.starts_with(p)) {
        return Ok(None);
    }
    let token = PortfolioToken::query()
        .filter(PortfolioToken::token_hash.eq(sha256_hex(raw)))
        .filter(PortfolioToken::revoked_at.is_null())
        .first()
        .await?;
    Ok(token.filter(|t| !t.is_expired()))
}

The database stores only the sha256 of the token, so Rust and PHP find the same row and agree on whether the token is still alive.

Rate limits are more interesting. In PHP this route has three:

  • per IP — up to 1800 requests a minute with a token and 120 without one;
  • per token — 60 requests a minute;
  • bad tokens from one IP — 300 a minute, and only failed attempts count.

The last one maps to check and hit in Laravel Rust: first we check whether any quota is left, and we count the attempt only when it fails.

rust
let bad = format!("mcp-bad-token:{ip}");
let limit = Limit::per_minute(BAD_TOKENS_PER_MINUTE);
if let Err(too_many) = rate_limit::check(&bad, limit).await? {
    // 429 with Retry-After, the same JSON-RPC error as PHP
}
rate_limit::hit(&bad, limit).await?;

An important caveat: the Rust counters live in its own process and are not shared with PHP. A token that has already "spent" its limit on other PHP routes gets a fresh minute on this one. For a hook that fires once per commit, that is fine. But we have to keep it in mind as more routes move to Rust.


Who is on the team: roles and restricted projects

In PHP, the membership check is spread across three models: the project asks the team, the team asks the members table, and a restricted project also checks its own access list. In Rust we gathered it into one function that reads easily from top to bottom:

rust
async fn is_member(project: &ZoneProject, user_id: i64) -> laravel::Result<bool> {
    let Some(team_id) = project.team_id else {
        return Ok(false);
    };
    let Some(member) = TeamMember::query()
        .filter(TeamMember::team_id.eq(team_id) & TeamMember::user_id.eq(user_id))
        .first()
        .await?
    else {
        return Ok(false);
    };
    if !project.restricted || TeamMember::can_manage(&member.role) {
        return Ok(true);
    }
    let listed = ZoneMember::query()
        .filter(ZoneMember::project_id.eq(project.id) & ZoneMember::user_id.eq(user_id))
        .filter(ZoneMember::accepted_at.is_not_null())
        .first()
        .await?;
    Ok(listed.is_some())
}

The owner and admins see every project of the team. A regular member sees a restricted project only after being accepted into its access list. Someone else's project and a project that does not exist look the same — 404 Project not found. — so nobody can find out by brute force which projects exist.


The trick of the day: "not sure — hand it to PHP"

On day one, nginx sent a request to PHP only if Rust did not answer at all. Today we turned that into a rule. Rust itself answers 503 whenever it cannot answer exactly the way PHP would:

  • the Zones or MCP flag is turned off in its .env;
  • the database is unreachable;
  • any unexpected error happens.
rust
pub async fn check(Params(project): Params<String>, request: Request) -> Response {
    match handle(&project, &request).await {
        Ok(response) => response,
        Err(error) => {
            tracing::warn!(%error, "zones check failed; PHP answers instead");
            defer_to_php()
        }
    }
}

nginx sees the 503, intercepts it and quietly sends the same request to PHP. The user gets the right answer, and we get a line in the log. For a step-by-step move this is probably the most useful trick of all: Rust does not have to do everything from day one.


The check: 26 scenarios, zero surprises

We ran both services on one local database, created a test team, two projects (one open, one restricted), claims and five kinds of "bad" tokens, and sent the same requests to PHP and to Rust. We compared the status code, the body and the WWW-Authenticate header.

What we checked Answer PHP = Rust
No token, garbage, a foreign prefix, expired, revoked 401 + WWW-Authenticate ✅
Blocked account, unverified e-mail, no zones:read permission 403 ✅
Someone else's, non-existent or malformed project id; token bound to another project; restricted project without access 404 ✅
Empty path list, not a list, more than 500, numbers only, .., a control character, a path longer than 200 422 ✅
Conflicts, a clean list, id in upper case, a path with ./ and // 200 ✅

26 out of 26. Plus a nice detail: Rust updated the last-used time on exactly the five tokens that passed the check — just like PHP.

There is one honest mismatch. Send broken JSON with Content-Type: application/json, and Laravel Rust answers 400 before our code even runs, while PHP answers 422. The hook always sends valid JSON and handles any error the same way: it prints a message and lets the commit through. So we left it as is and added it to the list of known differences.


The scoreboard

  • Models: five in Rust on top of PHP tables — tokens, team members, the project access list, projects and claims. All read-only.
  • Code: one handler and seven unit tests for pure functions — parsing the Authorization header, path normalization, path overlap, time format.
  • The check: 26 scenarios with identical answers in PHP and Rust.

The route goes live in production the same way as the first one: the binary arrives through CI, and nginx gets one more location with a fallback to PHP.


What comes next

Day 3 — PHP sessions. Routes for logged-in users: Rust reads the session written by PHP and finds the user by login_web_…. Everything we worked out on day one about cookies and the payload finally goes to work.

After that, the plan is queues and jobs on a separate queue, then migrations and seeders. Each step is its own day in the series.


Links

Was this guide helpful?

Read next

// Newsletter

New Architecture guides by e-mail

One e-mail a week with new guides on Architecture. No spam, unsubscribe in one click.

About the author

Volodymyr Pichkurov View portfolio

Spotted a mistake? Suggest an edit

Help us improve this article. Suggest edits, additions, or corrections.

No suggestions submitted yet. Be the first to share your feedback!

On this page