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)
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:authorityaware, ignoreswww/api/adminby default). - Subdomain takes strict precedence over
X-Tenant-IDheader fallback (preventing header spoofing on tenant subdomains), and rejects duplicate/non-ASCII headers with400 Bad Request. - Automatically updates
laravel-rust'sTrustHostsmiddleware to allowmyapp.com,*.myapp.com,localhost,127.0.0.1, and the host fromAPP_URL. Disable with.without_auto_trust_hosts()if you manageTrustHostsmanually.
To disable header fallback completely in production (subdomain_only) or customize ignored subdomains:
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:
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):
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:
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(...)):
- Keep fail-closed DB protection enabled (
t.require_tenant(true), the default — orTenantConfig::require_tenant()if wiring manually). - Keep
ResolveTenantMiddlewareoptional (the default on.with_tenancy()— or.optional()when wiring manually). - Use
tenant: Option<Tenant>on public routes andtenant: Tenanton tenant routes:
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:
route.get("/invoices/{invoice}", |_tenant: Tenant, invoice: Invoice| async move {
Json(invoice)
});- Requesting
GET /invoices/2asacmeloads invoice #2 fromacme's database. - Requesting
GET /invoices/2asglobex(which has no invoice #2) returns404 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:
#[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"inacmesucceeds (200). - Creating
"INV-001"a second time inacmereturns422 Unprocessable Entity. - Creating
"INV-001"inglobexsucceeds (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 |