tenanted.dev v0.2.2
Guide 02 of 7

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

VariableDefaultPurpose
TENANT_DATABASE_URLsqlite://storage/tenants/{tenant}/main.sqlite3?mode=rwcPer-tenant database URL template. Must contain {tenant} (or %{tenant}). Alias: TENANT_DATABASE_URL_TEMPLATE.
TENANT_BASE_DOMAINInferred from APP_URL host (if non-loopback)Base domain for wildcard subdomain routing (acme.<domain>). Auto-configures TrustHosts for <domain> and *.<domain>.
TENANT_HEADERx-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_REQUIREtrueFail-closed guard: queries on tenanted models outside a tenant scope fail with NoTenant instead of hitting a shared DB.
TENANT_AUTO_CREATEfalse when APP_ENV=production, true otherwiseAutomatically create & migrate a tenant DB on first request. Keep false in production so bot traffic cannot create DBs.
TENANT_MAX_OPEN64Maximum open tenant connection pools cached in the LRU pool before least-recently-used idle pools are evicted.
TENANT_MAX_CONNECTIONS4Maximum SQLx connections per open tenant pool.
TENANT_CONTEXT_KEYtenantStructured 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

MethodSignatureWhat it does
databaset.database("sqlite://.../tenants/{tenant}/main.sqlite3?mode=rwc")Sets the per-tenant URL template (url_template is an alias).
central_connectiont.central_connection("central")Marks a central/landlord DB connection for users, orgs, and billing.
require_tenantt.require_tenant(true)Enables/disables fail-closed default connection guard (true by default).
auto_createt.auto_create(false)Controls whether unknown tenants are created on the fly (false in APP_ENV=production).
max_open_tenantst.max_open_tenants(128)Sets the LRU open-tenant pool capacity (default 64).
max_connections_per_tenantt.max_connections_per_tenant(4)Sets SQLx max_connections per tenant pool (default 4).

Resolution & HTTP Middleware

MethodSignatureWhat it does
subdomaint.subdomain("myapp.com")Resolves <tenant>.myapp.com and registers TrustHosts for myapp.com + *.myapp.com.
subdomain_onlyt.subdomain_only()Disables any HTTP header fallback so only subdomains resolve tenants (already the default on t.subdomain(...)).
with_header_fallbackt.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).
headert.header("x-tenant-id")Resolves tenants from a custom HTTP header.
sessiont.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_tenantt.resolve_tenant(|req| Box::pin(async move { ... }))Custom async tenant resolver closure (e.g. custom customer domains, JWT claims, API keys).
ignore_subdomainst.ignore_subdomains(["www", "api", "admin", "status"])Subdomains treated as central/untenanted (defaults to ["www", "api", "admin"]).
require_http_tenantt.require_http_tenant()Rejects every HTTP request without a resolved tenant (400 / 404), instead of leaving public routes untenanted.
on_web_middlewaret.on_web_middleware()Attaches tenant middleware to the web group (after sessions/cookies) instead of global middleware.
middlewaret.middleware(custom_mw)Replaces the auto-configured ResolveTenantMiddleware with a hand-built instance.
without_http_middlewaret.without_http_middleware()Disables automatic HTTP middleware registration (e.g. pure worker/CLI binaries or route-group-only middleware).
without_auto_trust_hostst.without_auto_trust_hosts()Opts out of automatic TrustHosts registration when managing TrustHosts yourself.

Migrations & Lifecycle Hooks

MethodSignatureWhat it does
create_tablet.create_table("projects", |table| { ... })Adds a transactional Laravel Blueprint CREATE TABLE migration (auto-named create_<table>_table).
create_table_namedt.create_table_named("0001_projects", "projects", |table| { ... })Explicit migration name for strict ordering.
alter_tablet.alter_table("0002_add_slug", "projects", |table| { ... })Adds a transactional Blueprint ALTER TABLE migration.
schema_migrationt.schema_migration("0003_custom", |schema| Box::pin(...))Runs arbitrary async schema builder operations inside a tenant migration.
sql_migrationt.sql_migration("0004_idx", "CREATE INDEX ...")Runs raw SQL inside a tenant migration.
migrationt.migration(custom_migration)Registers any IntoTenantMigration implementation.
check_existst.check_exists(|tenant_id| Ok(exists))Custom existence check (used when auto_create(false) for Postgres/S3/R2 backends).
discover_tenantst.discover_tenants(|| Ok(vec![...]))Custom tenant discovery callback powering tenant:list and tenant:migrate --all.
on_deletet.on_delete(|tenant_id| Ok(()))Cleanup hook called by tenant:delete <id> --force (e.g. DROP DATABASE or S3 shred).

Cache, Storage, Commands & Advanced

MethodSignatureWhat it does
keep_default_cachet.keep_default_cache()Registers the "tenanted" cache store without replacing your app's default cache store.
allow_untenanted_cachet.allow_untenanted_cache()Allows cache calls outside a tenant scope (e.g. login rate-limiters and public pages) using a "global:" namespace.
without_tenanted_cachet.without_tenanted_cache()Skips registering the "tenanted" cache store altogether.
storage_prefixt.storage_prefix("tenants")Custom prefix used by TenantedStorage (tenants/<id>/...).
cleanup_storage_diskt.cleanup_storage_disk("local")Automatically deletes a tenant's files from the named disk during tenant:delete.
without_commandst.without_commands()Skips registering the 5 tenant:* Artisan commands.
install_globalt.install_global()Installs the manager into the global laravel_tenanted::* handle even in non-global/test setups.
config_mutt.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:

.env
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::<String>("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 — 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 <slug>.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:[email protected]: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:[email protected]: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, laravel-tenanted, and laravel-litebucket:

Shell
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 (tenancy-org-switcher and litebucket-demo branches).