tenanted.dev v0.1.5
Guide 02 of 6

Tenant Resolution & Routing

laravel-tenanted supports subdomain, HTTP header, and custom closure resolution — plus first-class Tenant / Option<Tenant> 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 <tenant> from <tenant>.myapp.com (case-insensitive, port-stripped, trailing FQDN dot stripped, HTTP/2 :authority aware, ignores www/api/admin by default).
  • Subdomain takes strict precedence over X-Tenant-ID header fallback (preventing header spoofing on tenant subdomains), and rejects duplicate/non-ASCII headers with 400 Bad Request.
  • Automatically updates laravel-rust's TrustHosts middleware to allow myapp.com, *.myapp.com, localhost, 127.0.0.1, and the host from APP_URL. Disable with .without_auto_trust_hosts() if you manage TrustHosts manually.

To disable header fallback completely in production (subdomain_only) or customize ignored subdomains:

Rust
laravel::Application::configure()
    .with_tenancy_using(|t| {
        t.subdomain("myapp.com")
            .ignore_subdomains(["www", "api", "admin", "status"])
            .subdomain_only();
    })

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 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 (`/<tenant>/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<Tenant> 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<Tenant>) -> Json<serde_json::Value> {
    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<Json<serde_json::Value>> {
    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 VariantHTTP StatusWhen It Fires
TenantedError::MissingTenant400 Bad RequestRequired middleware or Tenant extractor ran with no tenant
TenantedError::InvalidTenantId400 Bad RequestTenant ID failed sanitize_tenant_id (e.g. ../evil)
TenantedError::TenantNotFound404 Not FoundUnknown tenant when auto_create(false) (or delete on missing tenant)
TenantedError::TenantAlreadyExists409 Conflictcreate("acme") / tenant:create acme called for an existing tenant
TenantedError::NoTenant500 Internal Server ErrorCode requiring a tenant (cache, job middleware, require()) ran outside a tenant scope
TenantedError::MigrationFailed500 Internal Server ErrorA tenant migration returned an error