tenanted.dev v0.1.5
Guide 01 of 6

Getting Started & Architecture

laravel-tenanted brings database-per-tenant multi-tenancy to laravel-rust without forcing custom query wrappers, global locks, or process-per-tenant compromises.

How It Works Under the Hood

In a PHP-FPM app, multi-tenancy packages mutate the process's default database connection because each HTTP request runs in its own isolated PHP process. laravel-rust is a long-lived async Tokio server handling thousands of concurrent requests inside one binary — mutating a process-global default connection would race and leak Tenant A's data into Tenant B's request.

Instead, laravel-tenanted builds directly on four native laravel-rust primitives:

  1. Dynamic Connections (DatabaseManager::add_connection / purge / remove_connection) Each tenant gets a named connection pool (tenant_acme, tenant_globex, ...) registered lazily on first touch and bounded by an LRU cache (max_open_tenants).
  2. Task-Local Connection Routing (DatabaseManager::using_connection) Entering a tenant scope wraps the request/job future in db.using_connection("tenant_acme", ...). Inside that async task — and any child tasks started with laravel::task::spawn — every #[model], create!, db::table(), db::query!(), db::transaction(), Route Model Binding lookup, and DB validation rule automatically routes to tenant_acme. Meanwhile, any model declaring an explicit connection (#[model(connection = "central")]) ignores the default connection override and keeps querying the central database.
  3. Request & Job Context (laravel::context) Entering a tenant scope writes tenant = "acme" into laravel::context (and restores the previous value via an RAII drop guard on exit, error, or cancellation). Every structured log line automatically carries tenant="acme", and every dispatched laravel::queue job automatically serializes that context to the worker.
  4. Fail-Closed Sentinel (TenantConfig::require_tenant()) When enabled, TenantedServiceProvider::boot points the process's default database connection to a sentinel name (no_active_tenant (...)) that is intentionally undefined. Any accidental query against a tenanted model outside a tenant scope fails immediately instead of silently reading or writing the default database.
Text
Incoming Request (acme.myapp.com)
        │
        ▼
  TrustHosts (auto-configured for myapp.com & *.myapp.com)
        │
        ▼
  ResolveTenantMiddleware
    ├── sanitize_tenant_id("acme")  → rejects .., /, \, spaces (400 Bad Request)
    ├── TenantManager::connection() → lazy register + migrate + LRU evict if full
    ├── laravel::context::add("tenant", "acme")
    ├── dispatch TenantEntered event
    └── db.using_connection("tenant_acme", next.run(request))
            │
            ▼
      Your Controller (100% vanilla laravel-rust!)
        ├── Invoice::query()                  → tenant_acme
        ├── create!(Invoice { ..input })      → tenant_acme
        ├── laravel::cache::get("dashboard")  → tenant:acme:dashboard
        ├── SendReceipt.dispatch()            → carries tenant="acme" in Context
        └── BillingPlan::query()              → central DB (#[model(connection = "central")])

Adding laravel-tenanted to an Existing laravel-rust App

1. Add the Dependency

TOML
# Cargo.toml (SQLite default)
[dependencies]
laravel-tenanted = "0.1"

If your app uses PostgreSQL or MySQL and does not need SQLite:

TOML
[dependencies]
laravel-tenanted = { version = "0.1", default-features = false, features = ["postgres"] }

2. Enable Tenancy in 1 Line

Import WithTenancy and call .with_tenancy() right on laravel::Application::configure() — the exact same fluent style as .with_routing(...) and .with_middleware(...):

Rust
use laravel_tenanted::WithTenancy;

laravel::Application::configure()
    .with_tenancy()
    .with_routing(...)
    .run()

Or customize your subdomain / session resolver and tenant tables inline with .with_tenancy_using(|t| ...):

Rust
use laravel_tenanted::WithTenancy;

laravel::Application::configure()
    .with_tenancy_using(|t| {
        t.subdomain("myapp.com")
            .auto_create(false) // reject unknown tenants with 404
            .create_table("invoices", |table| {
                table.id();
                table.string("label").unique();
                table.big_integer("cents");
            });
    })
    .with_routing(...)
    .run()

With .with_tenancy() / .with_tenancy_using(...), laravel-tenanted automatically wires:

  • Database template & pool limits from env vars (defaulting to sqlite://storage/tenants/{tenant}/main.sqlite3?mode=rwc, max_open_tenants = 64, max_connections_per_tenant = 4)
  • Fail-closed mode (require_tenant) enabled by default so accidental queries outside a tenant scope fail loudly instead of leaking data
  • ResolveTenantMiddleware + TrustHosts auto-configured from TENANT_BASE_DOMAIN / APP_URL (ignoring www, api, admin), with X-Tenant-ID header fallback (call .subdomain_only() to disable header fallback)
  • Tenant-isolated "tenanted" cache store registered and set as the default cache store (opt out with .keep_default_cache() or .without_tenanted_cache())
  • All 5 tenant:* Artisan commands (tenant:create, tenant:list, tenant:migrate, tenant:evict, tenant:delete)

Environment Variables Recognized Automatically

VariableDefaultPurpose
TENANT_DATABASE_URLsqlite://storage/tenants/{tenant}/main.sqlite3?mode=rwcURL template containing {tenant} (also reads TENANT_DATABASE_URL_TEMPLATE)
TENANT_BASE_DOMAINInferred from APP_URLSubdomain base host (e.g. myapp.com → acme.myapp.com)
TENANT_HEADERx-tenant-idHeader fallback name (set empty to disable)
TENANT_AUTO_CREATEfalse in APP_ENV=production, true locallyfalse rejects unknown tenants with 404
TENANT_REQUIREtrueFail closed on queries outside a tenant scope
TENANT_MAX_OPEN64LRU cap on open tenant pools in RAM
TENANT_MAX_CONNECTIONS4Max connections per open tenant pool
TENANT_CONTEXT_KEYtenantlaravel::context key used for logs, jobs, cache & storage
TENANT_CENTRAL_CONNECTION(unset)Central DB connection name for without_tenant(...)
Manual registration with TenantConfig + TenantedServiceProvider

If you prefer explicit provider wiring (e.g. building TenantConfig dynamically in another module):

Rust
use laravel_tenanted::{TenantConfig, TenantedServiceProvider};

let tenancy = TenantConfig::new("sqlite://storage/tenants/{tenant}/main.sqlite3?mode=rwc")
    .require_tenant()
    .central_connection("central")
    .auto_create(false)
    .max_open_tenants(64)
    .max_connections_per_tenant(4)
    .create_table("invoices", |table| {
        table.id();
        table.string("label").unique();
        table.big_integer("cents");
    });

laravel::Application::configure()
    .with_providers(|providers| {
        providers.add(
            TenantedServiceProvider::new(tenancy)
                .resolve_from_subdomain("myapp.com"),
        );
    })
    .run()

3. Provision Your First Tenant

When auto_create(true) (default locally; defaults to false when APP_ENV=production), the first request to acme.myapp.com creates and migrates storage/tenants/acme/main.sqlite3 automatically.

If auto_create(false) (recommended for production SaaS where tenants sign up through a provisioning flow):

Shell
cargo run -- tenant:create acme

Or programmatically during customer onboarding:

Rust
laravel_tenanted::create("acme").await?;

Security & Tenant ID Validation

Every tenant identifier passes through laravel_tenanted::sanitize_tenant_id before any URL template rendering, file path creation, or connection lookup:

  • Length: 1..=63 characters (DNS subdomain compatible)
  • Characters: ASCII lowercase [a-z0-9_-], starting with alphanumeric
  • Normalized to lowercase ("Acme_01" → "acme_01")
  • Rejects path traversal (../globex, acme/evil, \), whitespace, null bytes, and control characters with TenantedError::InvalidTenantId (400 Bad Request).

Next Steps