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:
- 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.1"If your app uses PostgreSQL or MySQL and does not need SQLite:
[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(...):
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), withX-Tenant-IDheader 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
| 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).