Skip to content

Configuration

switchTenant()

switchTenant() — returns void

Available in: controller, model, mapper, migrator, migration, tabledefinition Category: Multi-Tenancy

Switches the active tenant mid-request. Throws if the current tenant is locked (set by TenantResolver middleware) unless force is true.

NameTypeRequiredDefaultDescription
tenantstructyes—Struct with at minimum a dataSource key. Optional: id, config.
forcebooleannofalseIf true, overrides the lock set by TenantResolver middleware.
// 1. Switch to a different tenant mid-request (minimal required argument)
switchTenant(tenant = {dataSource = "tenant_db_acme"});

// 2. Switch with a full tenant struct (id and per-tenant config override)
switchTenant(
    tenant = {
        dataSource = "tenant_db_beta",
        id         = "beta",
        config     = {timeZone = "America/New_York"}
    }
);

// 3. Force-switch even when the current tenant is locked by TenantResolver middleware
switchTenant(
    tenant = {dataSource = "tenant_db_admin", id = "admin"},
    force  = true
);