Skip to content

Exploring Laravel Rust ORM: Database Models, Queries and Migrations

Exploring Laravel Rust ORM: Database Models, Queries and Migrations

If you're used to Eloquent, a database model feels simple: define a class, add a migration, declare a relationship, and start querying. Laravel Rust keeps that familiar workflow, but changes the contract between your code and the database.

Instead of relying on runtime conventions alone, its ORM uses Rust structs and typed column definitions so many mistakes can be caught while the application is compiled. Relationships are explicit, queries are asynchronous, and migrations are compiled into the application binary.

The result is recognisably Laravel, but not Eloquent translated line by line. Let's build a small posts example and look at what that means for everyday database work.

Version note: Laravel Rust was released in beta on December 1, 2026. The examples below follow the official documentation available on December 3, 2026. APIs may change before version 1.0.

1. Start with the table: Laravel Rust migrations

In Laravel PHP, you might create a migration with php artisan make:migration. Laravel Rust uses its new CLI:

laravel make:migration create_posts_table

The command creates a timestamped Rust file inside database/migrations/. The timestamp determines execution order, just as it does in Laravel PHP.

A migration defines a single public migrate function. Here's a practical posts table with an author, title, slug, optional body, vote count and publication date:

// database/migrations/2026_10_27_143000_create_posts_table.rs

use laravel::db::AnyTransaction;

pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
    tx.schema()
        .create("posts", |table| {
            table.id();
            table.foreign_id("user_id").constrained().cascade_on_delete();

            table.string("title");
            table.string("slug").unique();
            table.text("body").nullable();

            table.integer("votes").default(0);
            table.timestamp("published_at").nullable();

            table.timestamps();
            table.index(["user_id", "published_at"]);
        })
        .await
}

A few familiar schema-builder ideas are here:

  • table.id() creates the primary key.
  • foreign_id("user_id").constrained() creates a foreign key to users.id by convention.
  • nullable() allows a column to contain NULL.
  • default(0) defines a database default.
  • unique() creates a unique index.
  • index([...]) creates a composite index.

The important part is that this is a portable schema definition. Laravel Rust's schema builder generates database-specific SQL for PostgreSQL, MySQL, MariaDB and SQLite. You don't need to write a separate CREATE TABLE statement for each of those engines.

Run the migration with:

laravel migrate

Laravel records completed migrations in a migrations table and runs only the pending ones. The migration files are compiled into the application binary, so a deployed application can run its migrations without shipping the original Rust source files.

There is one migration difference worth knowing before you get too comfortable: Laravel Rust migrations are forward-only. There is no down() function or rollback command. If a schema change needs to be reversed after it has been deployed, write another migration that makes the new change.

That is a deliberate safety choice, but it changes how you plan releases. Don't treat a migration as a temporary script you can casually roll back after production data has changed.

There are also database-specific details. A failed migration can roll back its schema changes on PostgreSQL and SQLite when it uses the normal transaction-based signature. MySQL and MariaDB implicitly commit around DDL statements such as CREATE TABLE, so a failure can leave earlier statements applied. The official guide recommends keeping each table change in its own migration file on those engines.

For more, see the Laravel Rust migrations guide and schema builder documentation.

2. Define a model that matches the database

Once the table exists, create a model in src/models/. A Laravel Rust model is a Rust struct annotated with #[model].

// src/models/post.rs

use laravel::model::{BelongsTo, HasMany, model};
use laravel::time::Timestamp;

use crate::models::{Comment, User};

#[model]
pub struct Post {
    pub id: i64,
    pub user_id: i64,
    pub title: String,
    pub slug: String,
    pub body: Option<String>,

    #[default]
    pub votes: i64,

    pub published_at: Option<Timestamp>,
    pub created_at: Timestamp,
    pub updated_at: Timestamp,

    #[belongs_to]
    pub user: BelongsTo<User>,

    #[has_many]
    pub comments: HasMany<Comment>,
}

If you've worked with Eloquent, the mapping is easy to recognise. The Post struct represents a row in the posts table, and its fields represent database columns.

But there are a few details worth slowing down for:

Nullable columns use Option<T>. The body and published_at fields can contain NULL, so they are represented as Option<String> and Option<Timestamp>. A non-nullable column maps to its corresponding Rust type.

Database defaults are declared with #[default]. The votes column has a default of zero in the migration. Marking the model field with #[default] tells the ORM that the value can be omitted when creating a post and supplied by the database.

Relationships are not columns. The user and comments fields describe how the model relates to other models. They do not create user or comments columns in the posts table. The actual foreign key is user_id.

Laravel follows conventions for table and column names: Post maps to posts, and a field named user_id maps to that column. You can override the table, primary key, column name or route key with model attributes when your existing schema doesn't follow those conventions.

The compiler can also check that the model's declared columns and types line up with the query operations you write. If votes is an integer, comparing it to a string is a type error rather than a mistake you discover only when a particular request runs.

The models documentation covers supported field types, UUIDs, ULIDs, enums, JSON columns and embedded values. For money, for example, the framework supports an exact Decimal type rather than requiring you to represent currency with a floating-point number.

3. Query models without guessing column names

This is where the ORM becomes particularly interesting.

In Eloquent, you write column names as strings:

Post::where('votes', '>=', 10)->get();

Laravel Rust generates typed column definitions from the model. Instead of passing a string column name, you refer to the field itself:

let posts = Post::query()
    .filter(Post::votes.ge(10))
    .filter(Post::published_at.is_not_null())
    .order_by(Post::published_at.desc())
    .limit(10)
    .get()
    .await?;

The query is still fluent, but Post::votes and Post::published_at are typed columns. Their comparison methods know what values are valid. A misspelled field or a comparison using the wrong Rust type can be caught during compilation.

You can combine conditions with & for AND, | for OR, and ! for negation:

let posts = Post::query()
    .filter(
        Post::published_at.is_not_null()
            & (Post::votes.ge(10) | Post::user_id.eq(user.id))
    )
    .order_by(Post::published_at.desc())
    .get()
    .await?;

Laravel compiles the expression into parameterised SQL with the intended grouping. You don't have to build nested closures just to make the AND/OR precedence clear.

A few useful retrieval methods:

// All rows
let posts = Post::all().await?;

// Find by primary key: returns Option<Post>
let post = Post::find(42).await?;

// Find or return a model-not-found error (HTTP handlers turn this into 404)
let post = Post::find_or_fail(42).await?;

// Paginate a query
let posts = Post::query()
    .order_by(Post::created_at.desc())
    .paginate(15)
    .await?;

For a single column, use pluck or value rather than loading full models:

let titles = Post::query()
    .order_by(Post::title)
    .pluck(Post::title)
    .await?;

That distinction matters. Model queries hydrate complete model structs, so they select all model columns; they don't expose select or add_select for partial model hydration. If a report needs only three columns, use the lower-level table query builder or map a raw query into a dedicated result struct instead of loading every field of every model.

4. Relationships: explicit loading instead of hidden queries

Laravel Rust supports familiar relationship patterns such as belongs_to, has_one, has_many and belongs_to_many, along with through and polymorphic relationships.

The Post model above declares that each post belongs to a user and can have many comments. A User model can declare the inverse:

use laravel::model::{HasMany, model};
use crate::models::Post;

#[model]
pub struct User {
    pub id: i64,
    pub name: String,
    pub email: String,

    #[has_many]
    pub posts: HasMany<Post>,
}

The most important behavioural difference is that relationships are not lazy-loaded automatically.

Imagine a page listing 25 posts with their authors. If each author lookup silently ran a query inside the loop, you could end up with 26 database queries: one for the posts and one for every author.

Instead, ask for the relationship when you build the query:

let posts = Post::query()
    .with(Post::user)
    .get()
    .await?;

for post in &posts {
    println!("{} by {}", post.title, post.user.name);
}

Laravel fetches the posts, then fetches the referenced users in one additional query and associates them with the posts. You can eager-load multiple relationships together:

let posts = Post::query()
    .with((Post::user, Post::comments))
    .get()
    .await?;

This makes the database work visible at the point where you shape the query. It helps avoid accidental N+1 queries, but it also means you need to decide which relationships a page actually needs. You can query a relationship directly when you don't want to load it with the parent model.

The framework also supports nested eager loading and constrained relationship queries. For example, you can load a user's three most recent published posts rather than every post. When you apply a limit to an eager-loaded relationship, the limit applies per parent record; include an order to make the selection deterministic.

See the Laravel Rust model relationships guide for the full set of relationship options.

5. Creating, updating and deleting records

Creating a model uses the create! macro. It checks that required fields are supplied and returns the stored model with its generated key, timestamps and database defaults populated.

use laravel::model::create;

let post = create!(Post {
    title: "Understanding typed queries",
    slug: "understanding-typed-queries",
    user: &user,
})
.await?;

Because votes has #[default], you don't need to provide it. The database supplies zero. The user: &user relationship sets the user_id foreign key.

For an update, use update!:

use laravel::model::update;

update!(post {
    title: "A better guide to typed queries",
})
.await?;

Laravel writes only the fields that changed and maintains updated_at. It also provides bulk update and delete operations, which are useful when you need to modify many rows without loading every model first.

That convenience has a consequence: bulk query writes skip model hooks and events because they operate directly in SQL. If you rely on a model hook to create a slug, enforce a business invariant or block an update, don't assume a bulk update will run that logic. Use instance-level writes when those hooks matter, or enforce critical rules at the database/service layer as appropriate.

One more detail before returning models from an API: #[model] derives serialization, and by default every column on the struct is included in the output. Mark internal fields with #[serde(skip)], and use a dedicated response struct when an endpoint should expose a deliberately limited shape. The framework also protects sensitive wrapper types such as PasswordHash and Encrypted<T> from accidental serialization.

6. When the ORM isn't enough: query builder, raw SQL and transactions

An ORM should make common operations convenient, not force every database operation into a model.

Laravel Rust also provides a fluent table query builder and a db::query! macro for SQL that is clearer to write directly. The macro lets you capture Rust variables inside braces:

use laravel::db;

let email = "reader@example.com";

let row = db::query!(
    "SELECT id, name FROM users WHERE email = {email}"
)
.select_one()
.await?;

Captured values are bound as query parameters; they are not concatenated into the SQL string. That is important for SQL injection protection. For lists, the macro supports an expansion form such as {...roles}, binding one parameter for each value.

For custom result shapes, derive db::FromRow on a struct and use select_as. This is also a good option when you need a projection rather than a complete ORM model.

For operations that must succeed or fail together, use a transaction. The database guide's example is a funds transfer: debit one account, credit another, and commit only if both updates succeed. db::transaction commits when its async closure returns Ok and rolls back when it returns an error.

That is the right place to think beyond query syntax. A type-safe query can still be part of an incorrect business operation if related writes are not grouped into a transaction.

What should Laravel developers take away?

Laravel Rust's ORM is not simply Eloquent with different punctuation. Its main idea is to make the relationship between a Rust model and its database schema more explicit.

Typed columns catch certain query mistakes before runtime. Explicit eager loading makes database access easier to see. The schema builder gives you portable migrations, while raw SQL remains available for queries that benefit from being written directly.

There are trade-offs. Model queries load complete models, bulk writes bypass hooks and events, and migrations are forward-only. The database driver list is also narrower than Laravel PHP's: the current Rust documentation lists PostgreSQL, MySQL, MariaDB and SQLite.

For a new Rust application, those are design choices worth understanding. For an existing Laravel PHP application, they are not reasons to rewrite it. Start by modelling one small feature, write its migration, query it, and see whether the stricter workflow suits your team.

The most useful ORM is not the one with the cleverest syntax. It's the one that makes the data access your application performs easy to understand, test and maintain.


Part B --- SEO package

SEO title: Laravel Rust ORM: Models, Queries & Migrations

Meta description: Learn how the Laravel Rust ORM handles typed models, database queries, relationships and forward-only migrations, with practical Rust examples.

URL slug: laravel-rust-orm-models-queries-migrations

Primary keyword: Laravel Rust ORM

Secondary keywords: - Laravel Rust models - Laravel Rust query builder - Laravel Rust migrations - Rust ORM - Laravel Rust relationships - Laravel Rust database

Featured image concept: A 16:9 editorial illustration of a database schema connecting users, posts and comments, with a Rust-inspired orange accent and clean code-editor-inspired visual details. Show the relationships and migration-to-model flow rather than a generic robot or floating code. Suggested size: 1200 × 675 px or larger.

Image alt text: Laravel Rust ORM illustration showing typed database models, relationships, queries and schema migrations.

Suggested internal links: 1. Laravel Eloquent Relationships: A Practical Guide to Avoiding N+1 Queries. 2. Laravel Database Migrations: Safe Schema Changes for Production. 3. SQL Query Optimization: Indexes, Joins and Execution Plans.

Update recommendation: Revisit this article when Laravel Rust reaches version 1.0. Recheck model/query APIs, migration behaviour, supported database drivers and any breaking changes.


Part C --- Sources and fact verification

  1. Laravel Rust --- Models
    Primary source for model declarations, field types, naming conventions, typed columns, retrieval, pagination, creation, updates, deletes, hooks and serialization.

  2. Laravel Rust --- Model Relationships
    Primary source for relationship declarations, eager loading, nested and constrained relationships, relationship queries and many-to-many relationships.

  3. Laravel Rust --- Schema Builder and Migrations
    Primary sources for schema definitions, indexes, foreign keys, migration generation, migration execution, forward-only behaviour, transactions and database-specific caveats.

  4. Laravel Rust --- Database and Introducing Laravel Rust
    Primary sources for supported database drivers, SQL queries, parameter binding, transactions and the framework's beta launch.

Verification notes:

  • Research reflects official Laravel documentation available on December 3, 2026. Laravel Rust was released in beta on December 1, 2026.
  • The documented first-party database drivers are PostgreSQL, MySQL, MariaDB and SQLite. Do not assume Laravel PHP's full database-driver list carries over.
  • Migrations are forward-only; there is no down() or rollback command in the current Rust migration system.
  • PostgreSQL and SQLite provide clean rollback for failed transaction-based migrations. MySQL and MariaDB can leave earlier DDL statements applied because DDL implicitly commits.
  • Bulk query updates and deletes bypass model hooks and events. Model-instance writes follow the model lifecycle.
  • Model queries hydrate all model columns. Use pluck, value, the table query builder or a custom FromRow result when a smaller projection is required.
  • Code examples are adapted from the official documentation and have not been independently compiled or executed. Check the current documentation before using them in a production project.
Discussion

Comments

No comments yet. Be the first to comment.

Browse the project library

Projects to explore next

Source-code projects from the KritiMyantra catalogue. Check each project's details before buying.

All projects