# laravel-tenanted > Structural multi-tenancy (database-per-tenant) for Laravel for Rust (`laravel-rust 0.2`). Every customer gets an isolated database with vanilla `laravel-rust` models, fail-closed safety, and zero `tenant_id` columns on tenant tables. - Crate: https://crates.io/crates/laravel-tenanted - Docs: https://tenanted.dev - Full LLM reference: https://tenanted.dev/llms-full.txt - GitHub: https://github.com/cole-robertson/laravel-tenanted - Live Demo: https://demo.tenanted.dev - Agent Skill: `npx skills@latest add cole-robertson/laravel-tenanted --skill laravel-tenanted` ## Quick Install ```sh cargo add laravel-tenanted # Optional: durable SQLite on S3 / Cloudflare R2 / Laravel Cloud Object Storage cargo add laravel-litebucket ``` ## Guides - [Getting Started & Architecture](https://tenanted.dev/docs/getting-started/): Why SQLite makes database-per-tenant practical, how `DatabaseManager::using_connection` + `laravel::context` + fail-closed `require_tenant()` work, and strict tenant ID validation. - [Configuration Reference & Real-World Recipes](https://tenanted.dev/docs/configuration/): All `TENANT_*` env vars, all 27 `TenancyBuilder` methods, Laravel Cloud + LiteBucket auto-setup, custom customer domains, Postgres schema-per-tenant, and shadcn UI SDK starter kit setup. - [Tenant Resolution & Routing](https://tenanted.dev/docs/resolution-and-routing/): Subdomains + `TrustHosts`, headers, sessions, custom `resolve_tenant`, `Tenant` / `Option` extractors, Route Model Binding, per-tenant validation, typed errors. - [Models, Migrations & Central Data](https://tenanted.dev/docs/models-migrations-and-central/): `#[model(connection = "central")]`, `without_tenant`, `run`, `for_each`, Blueprint migrations, LRU pooling, lifecycle hooks, 5 `tenant:*` Artisan commands. - [Queues, Cache, Storage, Events & Testing](https://tenanted.dev/docs/queues-cache-and-events/): `TenantQueueMiddleware`, `laravel::context` logs, `"tenanted"` cache store, `TenantedStorage`, lifecycle events, `TempTenants` parallel testing. - [Inertia + React Org Switcher](https://tenanted.dev/docs/inertia-org-switcher/): Full `.session("active_org")` org switcher + Super Admin inspection recipe. - [Deployment Guide](https://tenanted.dev/docs/deployment/): Laravel Cloud + LiteBucket auto-setup, Docker/VPS, Fly.io, wildcard TLS, backups, GDPR offboarding. --- # 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-tenanted` intentionally does **not** do shared-table row-level `tenant_id` scoping 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 via [`laravel-litebucket`](https://litebucket.dev)), 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 DATABASE` superuser 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-tenanted` with **[`laravel-litebucket`](https://litebucket.dev)** (`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](configuration.md). ## 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. ``` 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.2" ``` If your app uses PostgreSQL or MySQL and does not need SQLite: ```toml [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(...)`: ```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`), strictly subdomain-only by default so untrusted `X-Tenant-ID` headers on apex/ignored subdomains are ignored (call `.with_header_fallback("x-tenant-id")` or set `TENANT_HEADER=x-tenant-id` to 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): ```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): ```bash 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 - [Tenant Resolution & Routing](resolution-and-routing.md) - [Models, Migrations & Central Data](models-migrations-and-central.md) - [Queues, Cache, Events & Testing](queues-cache-and-events.md) - [Deployment Guide](deployment.md) --- # Configuration Reference & Real-World Recipes Every `laravel-tenanted` setting can be configured **from environment variables** (with zero Rust boilerplate via `.with_tenancy()`) or **fluently in code** via `.with_tenancy_using(|t| { ... })`. Code settings always override env defaults. --- ## 1. Environment Variables | Variable | Default | Purpose | |---|---|---| | `TENANT_DATABASE_URL` | `sqlite://storage/tenants/{tenant}/main.sqlite3?mode=rwc` | Per-tenant database URL template. Must contain `{tenant}` (or `%{tenant}`). Alias: `TENANT_DATABASE_URL_TEMPLATE`. | | `TENANT_BASE_DOMAIN` | Inferred from `APP_URL` host (if non-loopback) | Base domain for wildcard subdomain routing (`acme.`). Auto-configures `TrustHosts` for `` and `*.`. | | `TENANT_HEADER` | `x-tenant-id` (when no `TENANT_BASE_DOMAIN`) / disabled (when subdomain active) | HTTP header tenant resolver (or explicit header fallback alongside `TENANT_BASE_DOMAIN`). Set to empty (`TENANT_HEADER=`) to disable header resolution completely. | | `TENANT_REQUIRE` | `true` | Fail-closed guard: queries on tenanted models outside a tenant scope fail with `NoTenant` instead of hitting a shared DB. | | `TENANT_AUTO_CREATE` | `false` when `APP_ENV=production`, `true` otherwise | Automatically create & migrate a tenant DB on first request. Keep `false` in production so bot traffic cannot create DBs. | | `TENANT_MAX_OPEN` | `64` | Maximum open tenant connection pools cached in the LRU pool before least-recently-used idle pools are evicted. | | `TENANT_MAX_CONNECTIONS` | `4` | Maximum SQLx connections per open tenant pool. | | `TENANT_CONTEXT_KEY` | `tenant` | Structured logging key written into `laravel::context` (and propagated to queue jobs). | | `TENANT_CENTRAL_CONNECTION` | *(none)* | Optional named central/landlord connection (e.g. `"central"`). Excluded from tenant rewriting. | --- ## 2. `TenancyBuilder` Method Reference Every method available inside `Application::configure().with_tenancy_using(|t| { ... })`: ### Database & Pool | Method | Signature | What it does | |---|---|---| | `database` | `t.database("sqlite://.../tenants/{tenant}/main.sqlite3?mode=rwc")` | Sets the per-tenant URL template (`url_template` is an alias). | | `central_connection` | `t.central_connection("central")` | Marks a central/landlord DB connection for users, orgs, and billing. | | `require_tenant` | `t.require_tenant(true)` | Enables/disables fail-closed default connection guard (`true` by default). | | `auto_create` | `t.auto_create(false)` | Controls whether unknown tenants are created on the fly (`false` in `APP_ENV=production`). | | `max_open_tenants` | `t.max_open_tenants(128)` | Sets the LRU open-tenant pool capacity (default `64`). | | `max_connections_per_tenant` | `t.max_connections_per_tenant(4)` | Sets SQLx `max_connections` per tenant pool (default `4`). | ### Resolution & HTTP Middleware | Method | Signature | What it does | |---|---|---| | `subdomain` | `t.subdomain("myapp.com")` | Resolves `.myapp.com` and registers `TrustHosts` for `myapp.com` + `*.myapp.com`. | | `subdomain_only` | `t.subdomain_only()` | Disables any HTTP header fallback so only subdomains resolve tenants (already the default on `t.subdomain(...)`). | | `with_header_fallback` | `t.with_header_fallback("x-tenant-id")` | Explicitly opts in to an HTTP header fallback when subdomain resolution does not match (e.g. local dev or trusted API gateway). | | `header` | `t.header("x-tenant-id")` | Resolves tenants from a custom HTTP header. | | `session` | `t.session("active_org")` | Resolves tenants from a Laravel session key (ideal for SaaS org switchers). Automatically runs on the `web` middleware group after `StartSession`. | | `resolve_tenant` | `t.resolve_tenant(\|req\| Box::pin(async move { ... }))` | Custom async tenant resolver closure (e.g. custom customer domains, JWT claims, API keys). | | `ignore_subdomains` | `t.ignore_subdomains(["www", "api", "admin", "status"])` | Subdomains treated as central/untenanted (defaults to `["www", "api", "admin"]`). | | `require_http_tenant` | `t.require_http_tenant()` | Rejects every HTTP request without a resolved tenant (`400` / `404`), instead of leaving public routes untenanted. | | `on_web_middleware` | `t.on_web_middleware()` | Attaches tenant middleware to the `web` group (after sessions/cookies) instead of global middleware. | | `middleware` | `t.middleware(custom_mw)` | Replaces the auto-configured `ResolveTenantMiddleware` with a hand-built instance. | | `without_http_middleware` | `t.without_http_middleware()` | Disables automatic HTTP middleware registration (e.g. pure worker/CLI binaries or route-group-only middleware). | | `without_auto_trust_hosts` | `t.without_auto_trust_hosts()` | Opts out of automatic `TrustHosts` registration when managing `TrustHosts` yourself. | ### Migrations & Lifecycle Hooks | Method | Signature | What it does | |---|---|---| | `create_table` | `t.create_table("projects", \|table\| { ... })` | Adds a transactional Laravel Blueprint `CREATE TABLE` migration (auto-named `create__table`). | | `create_table_named` | `t.create_table_named("0001_projects", "projects", \|table\| { ... })` | Explicit migration name for strict ordering. | | `alter_table` | `t.alter_table("0002_add_slug", "projects", \|table\| { ... })` | Adds a transactional Blueprint `ALTER TABLE` migration. | | `schema_migration` | `t.schema_migration("0003_custom", \|schema\| Box::pin(...))` | Runs arbitrary async schema builder operations inside a tenant migration. | | `sql_migration` | `t.sql_migration("0004_idx", "CREATE INDEX ...")` | Runs raw SQL inside a tenant migration. | | `migration` | `t.migration(custom_migration)` | Registers any `IntoTenantMigration` implementation. | | `check_exists` | `t.check_exists(\|tenant_id\| Ok(exists))` | Custom existence check (used when `auto_create(false)` for Postgres/S3/R2 backends). | | `discover_tenants` | `t.discover_tenants(\|\| Ok(vec![...]))` | Custom tenant discovery callback powering `tenant:list` and `tenant:migrate --all`. | | `on_delete` | `t.on_delete(\|tenant_id\| Ok(()))` | Cleanup hook called by `tenant:delete --force` (e.g. `DROP DATABASE` or S3 shred). | ### Cache, Storage, Commands & Advanced | Method | Signature | What it does | |---|---|---| | `keep_default_cache` | `t.keep_default_cache()` | Registers the `"tenanted"` cache store without replacing your app's default cache store. | | `allow_untenanted_cache` | `t.allow_untenanted_cache()` | Allows cache calls outside a tenant scope (e.g. login rate-limiters and public pages) using a `"global:"` namespace. | | `without_tenanted_cache` | `t.without_tenanted_cache()` | Skips registering the `"tenanted"` cache store altogether. | | `storage_prefix` | `t.storage_prefix("tenants")` | Custom prefix used by `TenantedStorage` (`tenants//...`). | | `cleanup_storage_disk` | `t.cleanup_storage_disk("local")` | Automatically deletes a tenant's files from the named disk during `tenant:delete`. | | `without_commands` | `t.without_commands()` | Skips registering the 5 `tenant:*` Artisan commands. | | `install_global` | `t.install_global()` | Installs the manager into the global `laravel_tenanted::*` handle even in non-global/test setups. | | `config_mut` | `t.config_mut()` | Direct mutable escape hatch to the underlying `TenantConfig`. | | `TenancyBuilder::from_env()` | `TenancyBuilder::from_env()` | Constructs a builder pre-loaded from the environment variables above. | --- ## 3. Real-World Recipes ### Recipe A — Laravel Cloud + `laravel-litebucket` Auto-Setup (Zero Postgres, Zero Disk) Run database-per-tenant SQLite on **stateless Laravel Cloud containers** with zero Postgres server and zero persistent disk. Attach a Laravel Cloud Object Storage (Cloudflare R2) bucket to your environment and Laravel Cloud automatically injects `FILESYSTEM_ENDPOINT`, `FILESYSTEM_BUCKET`, `FILESYSTEM_ACCESS_KEY_ID`, `FILESYSTEM_SECRET_ACCESS_KEY`, and `FILESYSTEM_REGION` — `laravel-litebucket` discovers them automatically with **zero S3 credentials to copy-paste**. Set just two variables in your Laravel Cloud environment: ```dotenv LITEBUCKET_VFS=1 LITEBUCKET_ENCRYPTION_KEY=pass:replace-with-a-strong-secret-passphrase ``` **`Cargo.toml`:** ```toml [dependencies] laravel-rust = { version = "0.2", features = ["database-sqlite"] } laravel-tenanted = "0.2" laravel-litebucket = "0.2" ``` **`src/config/database.rs`** — strict zero-RPO central DB in R2 when `LITEBUCKET_VFS=1`, plain local SQLite in dev/tests: ```rust use laravel::config::database::{ConnectionConfig, Database}; use laravel::config::{self, Env}; #[config::section] fn database(env: &Env) -> Database { let mut database = Database::from_env(env); let use_litebucket = env .get::("LITEBUCKET_VFS") .map(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "1" | "true" | "yes")) .unwrap_or(false); let central_url = if use_litebucket { // Strict mode: every central auth/org commit is durable in R2 before returning laravel_litebucket::database_url_strict("central/main") } else { "sqlite://storage/database/central.sqlite3?mode=rwc".to_owned() }; database.default = "central".to_owned(); database .add_connection("central", ConnectionConfig::new(central_url)) .apply_env(env); database } ``` **`src/app.rs`** — 1-line `t.litebucket_from_env()` wires tenant URLs, per-tenant HKDF encryption, existence checks, discovery, and GDPR shred hooks when `LITEBUCKET_VFS=1`, while keeping local SQLite for `cargo test` and local dev: ```rust use laravel::foundation::ApplicationBuilder; use laravel::{Application, model}; use laravel_litebucket::prelude::*; use laravel_tenanted::WithTenancy; laravel::db::migrations!(fn migrations = "database/migrations"); pub fn configure() -> ApplicationBuilder { Application::configure() .with_litebucket() .with_migrations(migrations()) .with_tenancy_using(|t| { t.litebucket_from_env() .session("active_org") .central_connection("central") .auto_create(false) .allow_untenanted_cache() .create_table("projects", |table| { table.id(); table.string("name"); table.string("status").default("active"); table.timestamps(); }); }) .with_routing(|routing, _| { routing.web(routes::web::routes).health("/up"); }) } ``` > This exact pattern powers the live demo at **[demo.litebucket.dev](https://demo.litebucket.dev)** — running on Laravel Cloud with zero Postgres and zero persistent disk. --- ### Recipe B — Custom Customer Domains (`app.acmecorp.com`) + Subdomain Fallback Use `t.resolve_tenant(...)` to look up custom domains in your central database while falling back to `.myapp.com`: ```rust use laravel_tenanted::{WithTenancy, without_tenant}; Application::configure() .with_tenancy_using(|t| { t.central_connection("central") .auto_create(false) .without_auto_trust_hosts() // allow customer domains via your proxy/TLS layer .resolve_tenant(|req| { let host = req .headers() .get("host") .and_then(|v| v.to_str().ok()) .unwrap_or("") .split(':') .next() .unwrap_or("") .to_ascii_lowercase(); Box::pin(async move { // 1. Standard subdomain: acme.myapp.com if let Some(sub) = host.strip_suffix(".myapp.com") { if !matches!(sub, "" | "www" | "api" | "admin") { return Ok(Some(sub.to_string())); } return Ok(None); } // 2. Custom customer domain lookup against central DB without_tenant(async move { let domain = CustomDomain::query() .filter(CustomDomain::hostname.eq(host)) .filter(CustomDomain::verified.eq(true)) .first() .await?; Ok(domain.map(|d| d.tenant_slug)) }) .await }) }); }) ``` --- ### Recipe C — PostgreSQL Structural Isolation (Schema-per-Tenant on One Database) `laravel-tenanted` is built for **structural isolation** (zero `tenant_id` columns, zero row-level scoping bugs). While SQLite + `laravel-litebucket` is the primary target where database-per-tenant is genuinely free, on **PostgreSQL** you should usually isolate tenants by **schema inside a single Postgres database** (one server, one database — works on Laravel Cloud Postgres, Neon, and RDS without `CREATEDB` permissions): ```toml [dependencies] laravel-rust = { version = "0.2", features = ["database-postgres"] } laravel-tenanted = { version = "0.2", default-features = false, features = ["postgres"] } ``` ```rust Application::configure() .with_tenancy_using(|t| { // One Postgres server, ONE database (`myapp`), isolated schema per tenant via `search_path`: t.database("postgres://app:secret@db.internal:5432/myapp?options=-c%20search_path%3D%22tenant_{tenant}%22") .central_connection("central") .subdomain("myapp.com") .auto_create(false) .max_open_tenants(32) .max_connections_per_tenant(2) .check_exists(|tenant_id| { // Verify the tenant schema exists in `information_schema.schemata` // (or check your central `organizations` table) Ok(true) }) .discover_tenants(|| { // Query active tenant slugs from your central `organizations` table Ok(vec!["acme".into(), "globex".into()]) }) .on_delete(|tenant_id| { tracing::info!(tenant = tenant_id, "DROP SCHEMA IF EXISTS \"tenant_{tenant_id}\" CASCADE"); Ok(()) }); }) ``` > **Enterprise alternative (logical DB-per-tenant on one server):** If compliance requires separate logical databases on the same Postgres server (`CREATE DATABASE tenant_acme`, similar to PHP Laravel's `stancl/tenancy`), point `t.database(...)` at `"postgres://app:secret@db.internal:5432/tenant_{tenant}"` instead. > > **Looking for shared-table `tenant_id` / Postgres RLS?** That's a different architectural model — `laravel-tenanted` intentionally focuses on structural isolation (separate databases or schemas). --- ### Recipe D — Starting Fresh with shadcn's Official Laravel Rust UI SDK Kit Combine Laravel's Rust template, [shadcn's official UI SDK starter kit](https://github.com/shadcn/laravel-starter-kits/tree/main/rust-react), `laravel-tenanted`, and `laravel-litebucket`: ```bash laravel new my-saas --rust cd my-saas npx shadcn add shadcn/laravel-starter-kits/rust-react cargo add laravel-tenanted laravel-litebucket ``` Or clone the ready-to-deploy reference app with Auth + Org Switcher + Super-Admin + LiteBucket R2 already wired: **[cole-robertson/laravel-rust-shadcn](https://github.com/cole-robertson/laravel-rust-shadcn)** (`tenancy-org-switcher` and `litebucket-demo` branches). --- # Tenant Resolution & Routing `laravel-tenanted` supports subdomain, HTTP header, and custom closure resolution — plus first-class `Tenant` / `Option` controller extractors, Route Model Binding, and per-tenant validation. --- ## Resolution Strategies ### 1. Subdomain Resolution (`acme.myapp.com`) ```rust use laravel_tenanted::WithTenancy; laravel::Application::configure() .with_tenancy_using(|t| { t.subdomain("myapp.com"); }) ``` What this configures automatically: - Extracts `` from `.myapp.com` (case-insensitive, port-stripped, trailing FQDN dot stripped, HTTP/2 `:authority` aware, ignores `www`/`api`/`admin` by default). - **Subdomain-only by default** — untrusted `X-Tenant-ID` headers on apex or ignored subdomains (`www`/`api`/`admin`) are ignored unless you explicitly opt in via `.with_header_fallback("x-tenant-id")`. Duplicate/non-ASCII headers and `Host`/URI `:authority` mismatches are rejected with `400 Bad Request`. - Automatically updates `laravel-rust`'s `TrustHosts` middleware to allow `myapp.com`, `*.myapp.com`, and the host from `APP_URL` (plus `localhost`/`127.0.0.1` in non-production environments only). Disable with `.without_auto_trust_hosts()` if you manage `TrustHosts` manually. To customize ignored subdomains or explicitly opt in to an `X-Tenant-ID` header fallback (e.g. for local dev or trusted API gateways): ```rust laravel::Application::configure() .with_tenancy_using(|t| { t.subdomain("myapp.com") .ignore_subdomains(["www", "api", "admin", "status"]) .with_header_fallback("x-tenant-id"); }) ``` ### 2. Header Resolution (`X-Tenant-ID` / `X-Workspace-ID`) Ideal for APIs, mobile clients, or internal microservices: ```rust laravel::Application::configure() .with_tenancy_using(|t| { t.header("x-tenant-id"); }) ``` ### 3. Signed Session Resolution (`t.session("active_org")`) Ideal for SaaS apps with a sidebar organization/account switcher (including Inertia + React apps): ```rust laravel::Application::configure() .with_tenancy_using(|t| { t.session("active_org") .central_connection("central") .auto_create(false); }) ``` `t.session("active_org")` automatically attaches `ResolveTenantMiddleware` to the **`web` middleware group** (running right after `StartSession`) so it reads the active tenant from the encrypted Laravel session cookie. Public routes (`/login`, `/register`) pass through cleanly when the session key is absent. See the [Inertia + React Org Switcher Guide](inertia-org-switcher.md) for a full walkthrough including Super Admin org switching. ### 4. Custom Resolver Closure (`resolve_tenant`) The direct Rust equivalent of `activerecord-tenanted`'s `tenant_resolver = ->(request) { ... }`. Return `Some(tenant_id)` for tenant requests, or `None` for public/marketing/health routes: ```rust laravel::Application::configure() .with_tenancy_using(|t| { t.resolve_tenant(|req| { // Example: path-prefix tenancy (`//invoices`) let first_segment = req.path().trim_start_matches('/').split('/').next()?; if matches!(first_segment, "" | "health" | "signup" | "login") { return None; } Some(first_segment.to_owned()) }); }) ``` `.resolve_tenant(...)` automatically marks the middleware `.optional()` so returning `None` lets public routes run cleanly while tenant routes stay protected by `Tenant` extractors and `.require_tenant()`. --- ## Mixed Public & Tenant Routes (`.optional()` vs. `.required()`) Most SaaS apps serve public routes (`/`, `/health`, `/signup`, `/webhooks/stripe`) alongside tenant routes (`/invoices`, `/settings`). The cleanest `laravel-rust` pattern (already enabled by default when using `.with_tenancy()` / `.with_tenancy_using(...)`): 1. Keep fail-closed DB protection enabled (`t.require_tenant(true)`, the default — or `TenantConfig::require_tenant()` if wiring manually). 2. Keep `ResolveTenantMiddleware` optional (the default on `.with_tenancy()` — or `.optional()` when wiring manually). 3. Use `tenant: Option` on public routes and `tenant: Tenant` on tenant routes: ```rust use laravel::http::Json; use laravel_tenanted::Tenant; // Works with OR without a tenant (returns `null` on myapp.com, `"acme"` on acme.myapp.com): async fn health(tenant: Option) -> Json { Json(serde_json::json!({ "status": "ok", "tenant": tenant })) } // Automatically returns 400 Bad Request if no tenant is active: async fn list_invoices(tenant: Tenant) -> laravel::Result> { let invoices = Invoice::query().get().await?; Ok(Json(serde_json::json!({ "tenant": tenant, "invoices": invoices }))) } ``` Even if a developer forgets to add `tenant: Tenant` on a tenant route, `Invoice::query()` still fails closed against the `NO_TENANT_CONNECTION` sentinel (`TenantedError::is_no_tenant(&err) == true`) instead of leaking data. --- ## Route Model Binding (`invoice: Invoice`) `laravel-rust` Route Model Binding works **automatically per tenant** with zero extra code: ```rust route.get("/invoices/{invoice}", |_tenant: Tenant, invoice: Invoice| async move { Json(invoice) }); ``` - Requesting `GET /invoices/2` as `acme` loads invoice #2 from `acme`'s database. - Requesting `GET /invoices/2` as `globex` (which has no invoice #2) returns **`404 Not Found`** — eliminating cross-tenant IDOR bugs by construction. --- ## Per-Tenant Validation (`unique` & `exists`) `laravel-rust`'s database validation rules execute against the active tenant's connection automatically: ```rust #[laravel::input(fills = Invoice)] #[validate(anyone)] pub struct CreateInvoice { #[validate(required, unique(Invoice::label))] pub label: String, #[validate(required)] pub cents: i64, } ``` - Creating `"INV-001"` in `acme` succeeds (`200`). - Creating `"INV-001"` a second time in `acme` returns **`422 Unprocessable Entity`**. - Creating `"INV-001"` in `globex` succeeds (`200`) — uniqueness is scoped strictly to each tenant's database. --- ## Typed HTTP Errors (`#[derive(Status)]`) `TenantedError` implements `laravel::errors::Status`, so returning any error via `?` automatically renders JSON (for `Accept: application/json`) or HTML error pages with the proper HTTP status: | Error Variant | HTTP Status | When It Fires | |---|---|---| | `TenantedError::MissingTenant` | `400 Bad Request` | Required middleware or `Tenant` extractor ran with no tenant | | `TenantedError::InvalidTenantId` | `400 Bad Request` | Tenant ID failed `sanitize_tenant_id` (e.g. `../evil`) | | `TenantedError::TenantNotFound` | `404 Not Found` | Unknown tenant when `auto_create(false)` (or `delete` on missing tenant) | | `TenantedError::TenantAlreadyExists` | `409 Conflict` | `create("acme")` / `tenant:create acme` called for an existing tenant | | `TenantedError::NoTenant` | `500 Internal Server Error` | Code requiring a tenant (cache, job middleware, `require()`) ran outside a tenant scope | | `TenantedError::MigrationFailed` | `500 Internal Server Error` | A tenant migration returned an error | --- # 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. ### Native Schema Blueprint Migrations (Recommended) 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` 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:pass@db.internal/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()`): ```bash # 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 ``` --- # Queues, Cache, Storage, Events & Testing Database isolation is only half of safe multi-tenancy — background jobs, caches, file storage, structured logs, and tests must stay isolated too. `laravel-tenanted` wires directly into `laravel-rust`'s native subsystems for all five. --- ## Background Queue Jobs (`TenantQueueMiddleware`) Because `laravel-tenanted` writes the active tenant to `laravel::context` (`tenant = "acme"`), **`laravel::queue` automatically serializes the tenant into every dispatched job payload** — including chains, batches, retries, and `failed` hooks. Add `TenantQueueMiddleware` to any tenanted job's `middleware` method: ```rust use laravel::queue::{IntoMiddleware, Queueable, job}; use laravel_tenanted::TenantQueueMiddleware; #[derive(Queueable)] pub struct SendInvoiceReceipt { pub invoice_id: i64, } #[job(tries = 3)] impl SendInvoiceReceipt { fn middleware(&self) -> impl IntoMiddleware { // Fails closed with `TenantedError::NoTenant` if dispatched outside a tenant scope! TenantQueueMiddleware::required() } async fn handle(self) -> laravel::Result<()> { // 100% vanilla laravel-rust — automatically queries the dispatching tenant's DB! let invoice = Invoice::find_or_fail(self.invoice_id).await?; tracing::info!(invoice_id = invoice.id, "sent receipt"); Ok(()) } } ``` - Dispatching `SendInvoiceReceipt { invoice_id: 1 }.dispatch().await?` from an `acme` HTTP request automatically runs `handle()` inside `acme`'s database, cache, and log scope. - Dispatching it outside any tenant scope fails closed immediately with `TenantedError::NoTenant`. - For jobs that may run either inside a tenant or centrally, use `TenantQueueMiddleware::optional()`. --- ## Structured Logging (`laravel::context`) Every log line written inside a tenant request, `using_tenant(...)` block, or `TenantQueueMiddleware` job automatically carries `tenant = ""` via `laravel::context`. Customize the context key if desired: ```rust TenantConfig::new("...").context_key("workspace") ``` When the tenant scope exits (normally, via `?`, or via future cancellation), an RAII guard restores the previous context value so tenant tags never bleed between requests or nested scopes. --- ## Tenant-Scoped Caching Sharing one cache namespace across tenants is one of the most common sources of production data leaks. `laravel-tenanted` gives you two fail-closed ways to isolate cache keys and atomic locks: ### Option A: Native `"tenanted"` Cache Driver (Auto-Wired by `.with_tenancy()`) When you use `.with_tenancy()` or `.with_tenancy_using(...)`, `laravel-tenanted` **automatically** registers the `"tenanted"` cache driver and sets it as your default cache store! Now **vanilla `laravel::cache::get` / `put` / `forget` / `flush` / `lock`** automatically: - Prefix every cache key with `tenant:{id}:` and every atomic lock with `tenant:{id}:lock:` - Isolate `laravel::cache::flush()` strictly to the active tenant (without wiping other tenants or breaking active atomic locks!) - Invalidate all cached keys & locks for a tenant automatically on `TenantManager::delete(...)` so recreated tenant slugs never resurrect stale data - Fail closed with `TenantedError::NoTenant` if called outside a tenant scope To allow non-tenant cache calls under a `central:` prefix (or keep your existing default cache store): ```rust use laravel_tenanted::WithTenancy; laravel::Application::configure() .with_tenancy_using(|t| { t.allow_untenanted_cache(); // or `t.keep_default_cache()` }) ``` ### Option B: Wrapping Any Existing Store (Redis, Database, Memory) If your app already uses Redis or a database cache store, wrap it on demand with `laravel_tenanted::cache()`, `laravel_tenanted::cache_store("redis")`, or `tenants.cache_store("redis")` (on `Inject`, which also shares automatic `delete()` invalidation): ```rust use laravel::time::ToSpan; // Prefixes with `tenant:{current}:dashboard`; fails with `NoTenant` outside a tenant! laravel_tenanted::cache()?.put("dashboard", payload, 5.minutes()).await?; let cached: Option = laravel_tenanted::cache()?.get("dashboard").await?; // Or target a named Redis store explicitly (with `delete()` epoch invalidation): tenants.cache_store("redis")?.put("dashboard", payload, 5.minutes()).await?; ``` --- ## Tenant-Scoped File Storage (`TenantedStorage`) Prevent cross-tenant file leaks on local disks, S3, Cloudflare R2, or Laravel Cloud disks with `laravel_tenanted::storage()` and `laravel_tenanted::storage_disk("s3")`: ```rust // Wraps the default `laravel::storage::Disk` scoped to `tenants/{current}/`: let disk = laravel_tenanted::storage()?; disk.put("invoices/inv-001.pdf", pdf_bytes).await?; // Or target any named disk (`"s3"`, `"public"`, `"local"`, `"laravel_cloud"`): let s3 = laravel_tenanted::storage_disk("s3")?; let bytes = s3.get("avatars/avatar.png").await?; // Listings automatically strip `tenants/{current}/` so paths stay clean & tenant-relative: let files = s3.all_files("").await?; // e.g. ["avatars/avatar.png"] // Path traversal (`..`, `\`, null bytes) is strictly rejected! assert!(s3.get("../globex/avatars/avatar.png").await.is_err()); ``` Opt into automatic file cleanup when a tenant is deleted (GDPR offboarding): ```rust laravel::Application::configure() .with_tenancy_using(|t| { t.storage_prefix("tenants") // default: `tenants/{id}/...` .cleanup_storage_disk("s3") // deletes `tenants/{id}` on `delete()` .cleanup_storage_disk("local"); }) ``` Calling `laravel_tenanted::storage()` outside a tenant scope fails closed with `TenantedError::NoTenant`. --- ## Lifecycle Events `laravel-tenanted` dispatches six native `laravel::event` structs — all marked `#[event(at_dispatch)]` so listeners fire immediately even while a database transaction is open: | Event | Fields | Fired When | |---|---|---| | `TenantEntered` | `tenant`, `connection` | Entering `using_tenant` / `ResolveTenantMiddleware` | | `TenantExited` | `tenant` | Leaving a tenant scope | | `TenantCreated` | `tenant`, `connection` | `create(...)` / `tenant:create` finishes provisioning | | `TenantMigrated` | `tenant`, `applied: Vec` | One or more migrations finish applying | | `TenantEvicted` | `tenant` | An open pool is evicted by the LRU cap | | `TenantDeleted` | `tenant` | `delete(...)` / `tenant:delete` removes a tenant | Register listeners with standard `laravel-rust` `.with_events(...)`: ```rust use laravel::event::Event; use laravel_tenanted::TenantCreated; laravel::Application::configure() .with_events(|events, _| { events.listen(|ev: Event| async move { tracing::info!(tenant = %ev.tenant, "provisioning welcome seed data"); }); }) ``` --- ## Testing Multi-Tenant Applications Because `TenantedServiceProvider` binds `TenantManager` as a **per-`Application` DI singleton** (never relying on shared global state), parallel `#[tokio::test]` tests stay 100% isolated from each other. Use the built-in RAII `laravel_tenanted::testing::TempTenants` helper to spin up an isolated temporary directory of tenant SQLite databases that cleans itself up automatically on drop: ```rust use laravel::config::Env; use laravel::testing::MakesHttpRequests; use laravel_tenanted::{WithTenancy, testing::TempTenants}; #[tokio::test] async fn tenants_cannot_see_each_others_invoices() { let temp = TempTenants::new(); let app = laravel::Application::configure() .replace_env(Env::default()) .with_tenancy_using(|t| { t.database(temp.config().url_template) .header("x-tenant-id") .create_table("invoices", |table| { table.id(); table.string("label"); table.big_integer("cents"); }); }) .with_routing(|routing, _| { // ... your app routes ... }) .create(); app.post("/invoices") .header("x-tenant-id", "acme") .header("accept", "application/json") .json(serde_json::json!({ "label": "INV-1", "cents": 5000 })) .await .assert_ok(); // Globex cannot see Acme's invoice #1 (404 Not Found): app.get("/invoices/1") .header("x-tenant-id", "globex") .header("accept", "application/json") .await .assert_status(404); } ``` --- # Inertia + React Starter Kit: Org Switcher & Super-Admin Tenancy If you're building with the **`laravel-rust` + Inertia React starter kit** (`laravel-rust-shadcn`), you can add full database-per-tenant multi-tenancy — complete with a sidebar **Organization Switcher** and **Super-Admin org switching** — in minutes using `laravel-tenanted`'s built-in `.session("active_org")` resolver. --- ## Architecture Overview - **Central Database (`#[model(connection = "central")]`)**: `User`, `Organization`, and `OrganizationMembership` live in the shared central database so authentication (`auth.session::>()`) works seamlessly across every organization. - **Tenant Databases (default `#[model]`)**: Every business model (`Invoice`, `Project`, `Customer`, etc.) has **zero tenant columns and zero tenancy boilerplate** — each organization gets its own physical database (`tenants/{slug}/main.sqlite3` or `tenant_{slug}` on Postgres/MySQL). - **Signed Session Resolution (`t.session("active_org")`)**: `laravel-tenanted` attaches `ResolveTenantMiddleware` to the **`web` middleware group** (running right after `StartSession`) and reads `active_org` from the encrypted Laravel session cookie. Public routes (`/login`, `/register`, `/organizations/switch`) pass through untenanted, while every org route fails closed with `Tenant` / `require_tenant()`. --- ## 1. Enable Session Tenancy in `src/app.rs` Add `.with_tenancy_using(...)` directly on `Application::configure()` in `src/app.rs`: ```rust use laravel::foundation::ApplicationBuilder; use laravel::{Application, inertia, model}; use laravel_tenanted::WithTenancy; use crate::http::middleware::HandleInertiaRequests; use crate::models::User; use crate::routes; laravel::db::migrations!(fn migrations = "database/migrations"); pub fn configure() -> ApplicationBuilder { Application::configure() .with_migrations(migrations()) .with_schema(laravel::db::schema!("database/schema")) .with_auth(|auth, _| { auth.session::>(); }) .with_tenancy_using(|t| { t.session("active_org") .central_connection("central") .auto_create(false) .allow_untenanted_cache() // lets /login rate limiting run outside a tenant scope .cleanup_storage_disk("local") .create_table("projects", |table| { table.id(); table.string("name"); table.string("status").default("active"); table.timestamps(); }); }) .with_routing(|routing, _| { routing .web(routes::web::routes) .api(routes::api::routes) .health("/up"); }) .with_middleware(|middleware, _| { middleware.web(|web| { web.append(inertia::middleware(HandleInertiaRequests)); }); }) } ``` --- ## 2. Central Models (`User`, `Organization`, `OrganizationMembership`) Pin authentication & organization directory models to `"central"` so they work both inside and outside an active organization: ```rust use laravel::model::model; #[model(connection = "central")] pub struct User { pub id: i64, pub name: String, pub email: String, pub is_super_admin: bool, } #[model(connection = "central")] pub struct Organization { pub id: i64, pub slug: String, // e.g. "acme", "globex" — validated by `sanitize_tenant_id` pub name: String, } #[model(connection = "central")] pub struct OrganizationMembership { pub id: i64, pub user_id: i64, pub organization_id: i64, pub role: String, // "owner" | "admin" | "member" } ``` --- ## 3. Share Active Org & Switchable Orgs in `HandleInertiaRequests` Update `src/http/middleware/handle_inertia_requests.rs` so every Inertia page automatically receives the active org and the list of orgs the current user can switch into (including **all** orgs when `user.is_super_admin` is `true`!): ```rust use laravel::inertia::{self, Props, props}; use laravel::prelude::*; use serde_json::json; use crate::models::{Organization, OrganizationMembership, User}; pub struct HandleInertiaRequests; impl inertia::Middleware for HandleInertiaRequests { async fn share(&self, request: &Request) -> laravel::Result { let user: Option = request.user().await?; let active_slug = laravel_tenanted::current(); let organizations: Vec = match &user { Some(u) if u.is_super_admin => { // Super-admins can inspect and switch into any provisioned organization: Organization::query().order_by(Organization::name).get().await? } Some(u) => { let org_ids: Vec = OrganizationMembership::query() .filter(OrganizationMembership::user_id.eq(u.id)) .get() .await? .into_iter() .map(|m| m.organization_id) .collect(); if org_ids.is_empty() { Vec::new() } else { Organization::query() .filter(Organization::id.is_in(org_ids)) .order_by(Organization::name) .get() .await? } } None => Vec::new(), }; Ok(props! { name => laravel::config().app.name.clone(), auth => json!({ "user": user }), tenancy => json!({ "current_org": active_slug, "organizations": organizations, "is_super_admin": user.as_ref().is_some_and(|u| u.is_super_admin), }), status => request.session().ok().and_then(|s| s.get::("status")), }) } fn error_page(&self) -> Option<&str> { Some("Error") } } ``` --- ## 4. Org Switcher & Provisioning Routes Add two authenticated web routes — one to switch orgs (checking membership OR `is_super_admin`) and one to create & provision a brand-new organization database: ```rust use laravel::auth::Authenticated; use laravel::http::{Redirect, StatusCode}; use laravel::model::create; use laravel::session::Session; use laravel::validation::Valid; #[laravel::input] #[validate(anyone)] pub struct SwitchOrgInput { #[validate(required)] pub slug: String, } pub async fn switch_organization( auth: Authenticated, session: Session, Valid(input): Valid, ) -> laravel::Result { let clean_slug = laravel_tenanted::sanitize_tenant_id(&input.slug)?; let org = Organization::query() .filter(Organization::slug.eq(&clean_slug)) .first() .await? .ok_or_else(|| laravel::Error::status(StatusCode::NOT_FOUND, "Organization not found"))?; // Authorize: either a member of `org` OR a platform super-admin! if !auth.is_super_admin { let is_member = OrganizationMembership::query() .filter(OrganizationMembership::user_id.eq(auth.id)) .filter(OrganizationMembership::organization_id.eq(org.id)) .exists() .await?; if !is_member { return Err(laravel::Error::status( StatusCode::FORBIDDEN, "You do not belong to this organization", )); } } session.put("active_org", &org.slug); Ok(Redirect::to("/dashboard")) } pub async fn create_organization( auth: Authenticated, session: Session, Valid(input): Valid, ) -> laravel::Result { let clean_slug = laravel_tenanted::sanitize_tenant_id(&input.slug)?; // 1. Provision & migrate the physical tenant database: laravel_tenanted::create(&clean_slug).await?; // 2. Record the organization + owner membership in the central DB: let org = create!(Organization { slug: clean_slug.clone(), name: input.slug.clone(), }) .await?; create!(OrganizationMembership { user_id: auth.id, organization_id: org.id, role: "owner", }) .await?; // 3. Switch the user straight into their new organization: session.put("active_org", &org.slug); Ok(Redirect::to("/dashboard")) } ``` And inside your tenant routes (like `DashboardController`), write 100% vanilla `laravel-rust` code: ```rust use laravel::inertia::{Inertia, props}; use laravel_tenanted::Tenant; pub async fn dashboard(tenant: Tenant) -> laravel::Result { let projects = Project::query().get().await?; // automatically queries active org's DB! let files = laravel_tenanted::storage()?.all_files("").await?; // tenants/{org}/... Ok(Inertia::render("Dashboard", props! { org => tenant.into_inner(), projects => projects, files => files, })) } ``` --- ## 5. Sidebar `` Component (`AppLayout.tsx`) Drop this right into `` or `` in `resources/js/layouts/AppLayout.tsx`: ```tsx import { router, usePage } from '@inertiajs/react'; import { Building2Icon, CheckIcon, ChevronsUpDownIcon, ShieldIcon } from 'lucide-react'; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger, } from '@/components/ui/dropdown-menu'; import { SidebarMenuButton } from '@/components/ui/sidebar'; type Org = { id: number; slug: string; name: string }; export function OrgSwitcher() { const { tenancy } = usePage<{ tenancy: { current_org: string | null; organizations: Org[]; is_super_admin: boolean }; }>().props; const current = tenancy.organizations.find((o) => o.slug === tenancy.current_org); const switchTo = (slug: string) => { router.post('/organizations/switch', { slug }, { preserveState: false }); }; return (
{current?.name ?? 'Select workspace'} {tenancy.current_org ?? 'No workspace active'}
Workspaces {tenancy.is_super_admin && ( Super Admin )} {tenancy.organizations.map((org) => ( switchTo(org.slug)}> {org.name} {org.slug === tenancy.current_org && } ))}
); } ``` > [!TIP] > Notice `preserveState: false` on `router.post('/organizations/switch', ...)` — that guarantees Inertia flushes any previous workspace's client-side React state immediately when switching organizations! --- # Deployment Guide `laravel-tenanted` is designed to deploy cleanly across **every** Rust hosting topology — from a single $5 VPS running SQLite-per-tenant, to Fly.io / Kamal containers with persistent volumes, to stateless Laravel Cloud / Kubernetes pods running PostgreSQL or LiteBucket S3/R2 SQLite. --- ## 1. Choosing Your Production Architecture | Platform | Recommended Storage | Config Template | Notes | |---|---|---|---| | **Single VPS / Hetzner / Kamal** | Local SQLite on NVMe + `litebucket replicate` or Litestream WAL backup | `sqlite:///data/tenants/{tenant}/main.sqlite3?mode=rwc` | Zero DB server ops, sub-millisecond reads, mount `/data` volume | | **Fly.io / Render / Railway** | Local SQLite on persistent volume | `sqlite:///data/tenants/{tenant}/main.sqlite3?mode=rwc` | Single writer region or Fly Replay for multi-region | | **Laravel Cloud / Managed Postgres (Schema-per-Tenant)** | PostgreSQL (`default-features = false, features = ["postgres"]`) | `postgres://user:pass@host/myapp?options=-c%20search_path%3D%22tenant_{tenant}%22` | One Postgres server & one DB; no `CREATEDB` needed (or `.../tenant_{tenant}` for logical DB-per-tenant on one server) | | **Laravel Cloud / Ephemeral Containers (SQLite)** | LiteBucket S3/R2 SQLite VFS | `laravel-litebucket` (`t.litebucket()`) | Zero local disk required + per-tenant HKDF AES-256-GCM encryption | --- ## 2. Environment-Driven Configuration `.with_tenancy()` and `.with_tenancy_using(...)` read your environment variables automatically — no manual `std::env::var(...)` parsing required — so local dev, staging, and production run the exact same binary: ```dotenv APP_ENV=production APP_URL=https://myapp.com TENANT_BASE_DOMAIN=myapp.com TENANT_DATABASE_URL=sqlite:///data/tenants/{tenant}/main.sqlite3?mode=rwc TENANT_MAX_OPEN=64 # TENANT_AUTO_CREATE defaults to false automatically when APP_ENV=production ``` --- ## 3. Wildcard Subdomains, Reverse Proxies & `TrustHosts` When serving `.myapp.com`: 1. **DNS:** Add a wildcard `A` / `AAAA` / `CNAME` record for `*.myapp.com` pointing to your load balancer or server. 2. **TLS:** Issue a wildcard certificate (`*.myapp.com` + `myapp.com`) via Caddy, Cloudflare, Fly.io, or Let's Encrypt DNS-01. 3. **Preserve the `Host` header:** Ensure your reverse proxy forwards the original `Host` header (`proxy_set_header Host $host;` in Nginx; automatic in Caddy and Kamal Proxy). 4. **`TrustHosts`:** `.with_tenancy()` / `.with_tenancy_using(|t| { t.subdomain("myapp.com"); })` (and `TenantedServiceProvider::resolve_from_subdomain`) automatically configures `laravel-rust`'s `TrustHosts` middleware to allow `myapp.com` and `*.myapp.com`. If you pass a custom `TrustHosts` config in `.with_middleware(...)`, remember to include `"*.myapp.com"`. --- ## 4. Laravel Cloud Auto-Setup with LiteBucket (Zero Postgres, Zero Persistent Disk) If you deploy on **Laravel Cloud** and want database-per-tenant SQLite **without paying for a Postgres cluster or mounting a disk**: 1. **Attach a Laravel Cloud Object Storage (R2) bucket** to your environment. Laravel Cloud automatically injects `FILESYSTEM_ENDPOINT`, `FILESYSTEM_BUCKET`, `FILESYSTEM_ACCESS_KEY_ID`, `FILESYSTEM_SECRET_ACCESS_KEY`, and `FILESYSTEM_REGION`. `laravel-litebucket` discovers all of them automatically — **zero S3 credentials to copy-paste**. 2. **Set two environment variables** in Laravel Cloud: ```dotenv LITEBUCKET_VFS=1 LITEBUCKET_ENCRYPTION_KEY=pass:your-strong-secret-passphrase ``` 3. **Wire `.with_litebucket()` + `t.litebucket_from_env()`:** ```rust use laravel_litebucket::prelude::*; use laravel_tenanted::WithTenancy; Application::configure() .with_litebucket() .with_migrations(migrations()) .with_tenancy_using(|t| { t.litebucket_from_env() .central_connection("central") .auto_create(false); }) ``` 4. **Use strict durability for central auth/org tables** in `src/config/database.rs`: ```rust let central_url = if std::env::var("LITEBUCKET_VFS").as_deref() == Ok("1") { laravel_litebucket::database_url_strict("central/main") } else { "sqlite://storage/database/central.sqlite3?mode=rwc".to_owned() }; ``` When Laravel Cloud stops, hibernates, or redeploys your container, the fresh cold pod boots in ~1 second from zero local disk and hydrates both `central/main` and every `tenants//main` database directly from your R2 bucket with per-tenant HKDF AES-256-GCM encryption. See the [Configuration Reference](configuration.md) and [litebucket.dev](https://litebucket.dev) for full details. --- ## 5. Docker Deployment (Multi-Stage Rust Binary + Persistent Volume) A complete working `Dockerfile` and `fly.toml` live in [`examples/deployable-saas/`](../examples/deployable-saas/). The core pattern: ```dockerfile FROM rust:1.99-bookworm AS builder WORKDIR /app COPY . . RUN cargo build --release FROM debian:bookworm-slim RUN apt-get update && apt-get install -y ca-certificates curl && rm -rf /var/lib/apt/lists/* WORKDIR /app COPY --from=builder /app/target/release/my-saas /usr/local/bin/my-saas RUN mkdir -p /data/tenants ENV APP_ENV=production ENV APP_URL=https://myapp.com ENV TENANT_BASE_DOMAIN=myapp.com ENV TENANT_DATABASE_URL="sqlite:///data/tenants/{tenant}/main.sqlite3?mode=rwc" EXPOSE 8000 HEALTHCHECK --interval=15s --timeout=3s CMD curl -fsS http://127.0.0.1:8000/health || exit 1 CMD ["my-saas", "serve", "--host", "0.0.0.0", "--port", "8000"] ``` Run with a persistent volume mounted at `/data`: ```bash docker build -t my-saas . docker run -d --name my-saas \ -p 8000:8000 \ -v my-saas-data:/data \ -e TENANT_BASE_DOMAIN=myapp.com \ my-saas ``` --- ## 6. Production Checklist - **Keep fail-closed mode enabled** — `.with_tenancy()` enables `require_tenant` by default (or call `TenantConfig::require_tenant()` if registering manually), guaranteeing no controller, job, or command can accidentally query a tenanted model outside a tenant scope. - **Keep `.auto_create(false)` in production** — `.with_tenancy()` sets `auto_create(false)` automatically when `APP_ENV=production`, preventing random bots hitting `spam1234.myapp.com` from creating thousands of empty tenant databases on disk! Provision customers explicitly during onboarding via `laravel_tenanted::create(&slug).await?` or `tenant:create `. - **Size `max_open_tenants`** — Each open SQLite pool keeps a handful of file descriptors (`max_connections_per_tenant`) and SQLite page cache in RAM. `64`–`256` works smoothly on 512 MB–2 GB containers; raise `ulimit -n` if you run higher. - **Run eager migrations on deploy** — Execute `my-saas tenant:migrate --all` as a release/pre-start hook so every tenant schema is upgraded before traffic hits. - **Isolate your cache** — `.with_tenancy()` automatically registers the in-memory `"tenanted"` default cache store (`tenant:{id}:*`). For multi-instance deployments sharing **Redis**, wrap it with `laravel_tenanted::cache_store("redis")?` (or `TenantedCacheStore::new(redis_store)`). - **Backups & offboarding:** - For local SQLite, back up `/data/tenants/` continuously (e.g. `litebucket replicate --tenants-dir /data/tenants --per-tenant-key` or Litestream) — every tenant is an independent `.sqlite3` file you can restore or export individually! - For GDPR / customer offboarding, run `my-saas tenant:delete --force` (or wire `TenantConfig::on_delete` to `DROP DATABASE` / `litebucket shred`).