tenanted.dev v0.1.5
Guide 03 of 6

Models, Migrations & Central Data

With laravel-tenanted, every standard model is tenanted by default — and central (shared) models simply name their connection once.

Tenanted Models vs. Central Models

Tenanted Models (Default)

Declare normal #[model] structs without a connection attribute:

Rust
use laravel::model::model;

#[model]
pub struct Invoice {
    pub id: i64,
    pub label: String,
    pub cents: i64,
}

Inside any tenant HTTP request, queued job, or using_tenant(...) block:

  • Invoice::query(), Invoice::find(id), create!(Invoice { .. }), invoice.update(...), invoice.delete(), and all HasMany / BelongsTo relations automatically query the active tenant's database.
  • laravel::db::table("invoices"), laravel::db::query!(...), and laravel::db::transaction(async |tx| { ... }) automatically run on the active tenant's database.
  • Tasks spawned with laravel::task::spawn(async { ... }) inherit both the active database connection and laravel::context tenant value automatically.

Central (Shared) Models

For cross-tenant data (billing plans, global feature flags, tenant directory, custom domain mappings), declare the central connection explicitly on the model:

Rust
#[model(connection = "central")]
pub struct BillingPlan {
    pub id: i64,
    pub name: String,
}

And register that "central" connection in .with_config(...):

Rust
laravel::Application::configure()
    .with_config(|cfg, _| {
        cfg.database.default = "central".into();
        cfg.database.connections.insert(
            "central".into(),
            ConnectionConfig::new("sqlite://storage/central.sqlite3?mode=rwc"),
        );
    })

BillingPlan::query() and create!(BillingPlan { .. }) work both inside and outside a tenant scope — even when TenantConfig::require_tenant() is enabled.

Escaping & Switching Scopes

Temporarily Leaving a Tenant (without_tenant)

Sibling of laravel::model::without_events (and Rails' without_tenant). Temporarily switches db::using_connection to the central connection and clears the active tenant in laravel::context, then restores the outer tenant cleanly on exit:

Rust
let total_plans = laravel_tenanted::without_tenant(async {
    // Runs on the central DB with no active tenant:
    laravel::db::table("billing_plans").count().await
}).await?;
// Outer tenant scope is restored automatically here!

(Aliases laravel_tenanted::central(...) and laravel_tenanted::landlord(...) are also provided for developers coming from stancl/tenancy or spatie/laravel-multitenancy.)

Explicit Tenant Scopes (using_tenant / run / for_each)

Use these in Artisan commands, scheduled jobs, seeders, or tests where there is no incoming HTTP request:

Rust
// Run a block against one tenant (aliases: `run`, `with_tenant`, `using_tenant`):
laravel_tenanted::using_tenant("acme", async {
    create!(Invoice { label: "SEED-1", cents: 5000 }).await?;
    Ok(())
}).await?;

// Iterate across every discovered tenant:
laravel_tenanted::for_each(|tenant| async move {
    let count = Invoice::query().count().await?;
    tracing::info!(%tenant, count, "monthly audit");
    Ok(())
}).await?;

// Or iterate across an explicit slice of tenants:
laravel_tenanted::for_each_in(["acme", "globex"], |tenant| async move {
    tracing::info!(%tenant, "processing");
    Ok(())
}).await?;

Migrations

Tenant migrations run inside a database transaction and are recorded in Laravel's standard migrations(id, migration, batch) table so they are idempotent and forward-only.

Use .create_table(...) and .alter_table(...) directly on .with_tenancy_using(|t| ...) or TenantConfig — no Box::pin(async move { ... }) boilerplate required:

Rust
use laravel_tenanted::WithTenancy;

laravel::Application::configure()
    .with_tenancy_using(|t| {
        t.create_table("invoices", |table| {
            table.id();
            table.string("label").unique();
            table.big_integer("cents");
            table.timestamps();
        })
        .alter_table("2026_02_15_000002_add_paid_at_to_invoices", "invoices", |table| {
            table.timestamp("paid_at").nullable();
        });
    })

For multi-step transactional migrations (seeding rows, inspecting schema, running multiple statements in one transaction), use .schema_migration(...):

Rust
t.schema_migration("2026_03_01_000003_backfill_defaults", |tx| {
    Box::pin(async move {
        tx.schema()
            .alter("invoices", |table| {
                table.string("currency").default("USD");
            })
            .await
    })
});

Compile-Time Safe SQL Migrations

Rust
let config = TenantConfig::new("sqlite://storage/tenants/{tenant}/main.sqlite3?mode=rwc")
    .sql_migration(
        "2026_01_01_000001_create_invoices_table",
        "CREATE TABLE invoices (id INTEGER PRIMARY KEY AUTOINCREMENT, label TEXT NOT NULL, cents INTEGER NOT NULL)",
    );

Lazy vs. Eager Migration Rollouts

  • Lazy (Automatic): Whenever a tenant database is opened for the first time after a deploy, TenantManager checks for pending migrations and applies them once under an async lock before returning the connection.
  • Eager (Deploy Step): Run cargo run -- tenant:migrate --all during deployments (or laravel_tenanted::migrate("acme").await?) so all tenants are upgraded before receiving traffic.

Connection Pool Lifecycle & LRU Eviction

Opening one connection pool per tenant without bounds would exhaust file descriptors and RAM when you have thousands of customers. TenantManager enforces a strict LRU cap:

Rust
let config = TenantConfig::new("sqlite://storage/tenants/{tenant}/main.sqlite3?mode=rwc")
    .max_open_tenants(64)           // Max tenant pools kept open simultaneously
    .max_connections_per_tenant(4); // Max sqlx connections inside each tenant pool
  • When the 65th tenant arrives, the least-recently-used tenant pool is cleanly purged (DatabaseManager::purge + remove_connection) and a TenantEvicted event is dispatched.
  • Inspect live pool stats anytime by injecting Inject<TenantManager> and calling tenants.stats().
  • On graceful shutdown, call tenants.evict_all() to flush and close every open SQLite pool cleanly.

Default SQLite PRAGMAs

For local sqlite:// URLs, TenantManager automatically applies production-safe defaults on every opened connection (unless overridden with .init_sql(...)):

  • PRAGMA journal_mode = WAL
  • PRAGMA synchronous = NORMAL
  • PRAGMA busy_timeout = 5000
  • PRAGMA foreign_keys = ON

Custom Discovery, Existence & Deletion Hooks

For local SQLite templates (sqlite://storage/tenants/{tenant}/main.sqlite3), list_tenants(), exists(), and delete() work automatically out of the box (scanning the directory and cleaning up -wal/-shm sidecars on delete).

For PostgreSQL, MySQL, or S3/R2 (LiteVault), plug in your own hooks on TenantConfig:

Rust
let config = TenantConfig::new("postgres://user:[email protected]/tenant_{tenant}")
    .discover_tenants(|| {
        // Query your central `tenants` registry or list S3 prefixes
        Ok(vec!["acme".into(), "globex".into()])
    })
    .check_exists(|tenant| {
        // Check your central registry before opening (used when `auto_create(false)`)
        Ok(tenant == "acme" || tenant == "globex")
    })
    .on_delete(|tenant| {
        // Run DROP DATABASE or `litevault shred`
        tracing::info!(%tenant, "deleting remote tenant");
        Ok(())
    });

Built-In Artisan Commands

Automatically registered by TenantedServiceProvider (opt out with .without_commands()):

Shell
# Provision & migrate a new tenant database (409 error if it already exists)
cargo run -- tenant:create acme

# List discovered tenants + active/idle LRU pool stats
cargo run -- tenant:list

# Migrate one tenant or all discovered tenants
cargo run -- tenant:migrate acme
cargo run -- tenant:migrate --all

# Evict one or all open tenant connection pools from RAM
cargo run -- tenant:evict acme
cargo run -- tenant:evict --all

# Permanently delete a tenant database (requires --force)
cargo run -- tenant:delete acme --force