tenanted.dev v0.2.2
Guide 04 of 7

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)",
    );

Running Migrations Across Many Customer Databases

A common question with database-per-tenant is: "What happens when I have 500 or 10,000 customer databases and ship a schema change?" laravel-tenanted handles this at every scale with three complementary strategies:

1. Lazy on First Touch (Default — O(1) Deploys at Any Tenant Count)

Whenever a tenant database is opened for the first time after a deploy, TenantManager:

  1. Acquires a per-tenant async lock (lock_tenant(id)), so even if 100 concurrent requests hit acme on cold start, only one runs the migration while the others wait cleanly.
  2. Reads that tenant's migrations(id, migration, batch) table and executes only pending migrations inside a transaction.
  3. Caches the tenant as migrated in memory so subsequent requests hit a lock-free fast path.

Because dormant or churned customers aren't touched during deploy, deploy time stays flat whether you have 10 tenants or 50,000. On LiteBucket (S3 / R2 / Laravel Cloud), lazy migrations are especially fast — you never download dormant tenant buckets on deploy, and conditional-PUT fencing prevents two cold pods from double-applying a migration.

2. Eager Rollout (tenant:migrate --all)

Run cargo run -- tenant:migrate --all (or laravel_tenanted::migrate_all().await?) as a release step when you want every tenant upgraded immediately:

  • Uses list_tenants() (local SQLite directory scan, s3_discover_tenants(...) via t.litebucket(), or your custom discover_tenants hook).
  • Iterates through tenants while respecting TENANT_MAX_OPEN (LRU eviction) — migrating 5,000 SQLite databases stays bounded in RAM and file descriptors because idle pools are purged as the loop progresses.
  • Idempotent on partial failure: each tenant migration runs in its own transaction. If tenant #427 fails on a data constraint, #1–#426 stay migrated, #427 rolls back cleanly, and re-running tenant:migrate --all skips already-migrated tenants automatically.

3. Background Queue Fan-Out (10,000+ Tenants)

For very large fleets where you want eager backfills without blocking a release hook, enqueue one lightweight job per tenant onto a dedicated migrations queue while letting lazy-on-first-touch upgrade any active customer who arrives first:

Rust
for tenant in laravel_tenanted::list_tenants()? {
    MigrateTenantJob { tenant }.dispatch().on_queue("migrations").await?;
}

Zero-Downtime Rolling Deploys (Expand & Contract)

During rolling deploys (Laravel Cloud, Kubernetes, Fly.io), old and new pods overlap briefly while sharing the same tenant databases. Follow standard expand-and-contract ordering:

  1. Deploy 1 (Expand): Add nullable or defaulted columns / new tables. Both old and new pods run cleanly against the expanded schema.
  2. Deploy 2 (Switch & Backfill): Write/read the new column; backfill existing tenants with laravel_tenanted::for_each(...) or queued jobs.
  3. Deploy 3 (Contract): Drop the old column once all previous-version pods have drained.

Multi-Process & Multi-Replica Safety

  • Local SQLite: PRAGMA busy_timeout = 5000 + unique constraint on migrations.migration ensures concurrent processes serialize cleanly without SQLITE_BUSY errors.
  • LiteBucket (S3 / R2): litebucket-vfs fenced write leases + If-None-Match: * CAS prevent split-brain migrations across stateless pods.

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 (LiteBucket), 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 `litebucket 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