Getting Started & Architecture
laravel-tenanted is built around structural isolation by default — every customer gets their own isolated database (SQLite-first, like Basecamp's activerecord-tenanted, or an isolated Postgres schema/database) without custom query wrappers, global scopes, or WHERE tenant_id = ? bugs.
Scope & Philosophy:
laravel-tenantedintentionally does not do shared-table row-leveltenant_idscoping or Postgres RLS. We believe structural isolation (separate databases or schemas) is the cleanest, safest way to keep customer data separate — especially with SQLite (local or durable on S3/R2 vialaravel-litebucket), where database-per-tenant is effectively free. If you specifically want shared-table row-level multi-tenancy, use a separate row-level pattern or package.
Why SQLite Makes Database-per-Tenant Practical
Most developers hear "database-per-tenant" and picture spinning up thousands of Postgres databases, hitting max_connections, and paying for oversized clusters. SQLite flips every one of those tradeoffs:
- Zero idle cost: An inactive tenant's database is just a file (or S3/R2 prefix) — 0 RAM, 0 background processes, 0 open connections. With
laravel-tenanted's LRU pool cap (TENANT_MAX_OPEN=64), 500 active SQLite tenants ran in 43.8 MiB RSS and 65 file descriptors. - Sub-millisecond reads, zero network hops: Queries run in-process inside your Rust binary. Smaller per-tenant B-trees stay hot in memory, and one noisy tenant can never bloat indexes or starve another customer's queries.
- Instant provisioning: Creating a brand-new tenant database and running its schema takes ~1 ms (1,000+ tenants/sec) — no
CREATE DATABASEsuperuser privileges or control-plane API calls. - Per-tenant backup, PITR, export & GDPR erasure: Restore a single customer to 10 minutes ago without touching anyone else, hand an enterprise customer a complete dump of their data, or permanently erase a departing tenant by deleting one file (
tenant:delete acme --force). - Works on stateless clouds too: Ephemeral container disks used to be SQLite's one catch. Pair
laravel-tenantedwithlaravel-litebucket(t.litebucket()) and every tenant's SQLite database lives directly on S3 / Cloudflare R2 / Laravel Cloud Object Storage with per-tenant HKDF AES-256-GCM encryption, zero Postgres server, and zero persistent disk.
Prefer PostgreSQL or MySQL? laravel-tenanted supports structural isolation there too (Postgres schema-per-tenant on a single database via search_path, or logical database-per-tenant on one server) — see the Configuration Reference.
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:
- 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). - Task-Local Connection Routing (
DatabaseManager::using_connection) Entering a tenant scope wraps the request/job future indb.using_connection("tenant_acme", ...). Inside that async task — and any child tasks started withlaravel::task::spawn— every#[model],create!,db::table(),db::query!(),db::transaction(), Route Model Binding lookup, and DB validation rule automatically routes totenant_acme. Meanwhile, any model declaring an explicit connection (#[model(connection = "central")]) ignores the default connection override and keeps querying the central database. - Request & Job Context (
laravel::context) Entering a tenant scope writestenant = "acme"intolaravel::context(and restores the previous value via an RAII drop guard on exit, error, or cancellation). Every structured log line automatically carriestenant="acme", and every dispatchedlaravel::queuejob automatically serializes that context to the worker. - Fail-Closed Sentinel (
TenantConfig::require_tenant()) When enabled,TenantedServiceProvider::bootpoints 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.
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
# Cargo.toml (SQLite default)
[dependencies]
laravel-tenanted = "0.2"If your app uses PostgreSQL or MySQL and does not need SQLite:
[dependencies]
laravel-tenanted = { version = "0.2", 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(...):
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| ...):
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+TrustHostsauto-configured fromTENANT_BASE_DOMAIN/APP_URL(ignoringwww,api,admin), strictly subdomain-only by default so untrustedX-Tenant-IDheaders on apex/ignored subdomains are ignored (call.with_header_fallback("x-tenant-id")or setTENANT_HEADER=x-tenant-idto opt in)- 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
| Variable | Default | Purpose |
|---|---|---|
TENANT_DATABASE_URL | sqlite://storage/tenants/{tenant}/main.sqlite3?mode=rwc | URL template containing {tenant} (also reads TENANT_DATABASE_URL_TEMPLATE) |
TENANT_BASE_DOMAIN | Inferred from APP_URL | Subdomain base host (e.g. myapp.com → acme.myapp.com) |
TENANT_HEADER | x-tenant-id | Header fallback name (set empty to disable) |
TENANT_AUTO_CREATE | false in APP_ENV=production, true locally | false rejects unknown tenants with 404 |
TENANT_REQUIRE | true | Fail closed on queries outside a tenant scope |
TENANT_MAX_OPEN | 64 | LRU cap on open tenant pools in RAM |
TENANT_MAX_CONNECTIONS | 4 | Max connections per open tenant pool |
TENANT_CONTEXT_KEY | tenant | laravel::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):
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):
cargo run -- tenant:create acmeOr programmatically during customer onboarding:
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..=63characters (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 withTenantedError::InvalidTenantId(400 Bad Request).