How does CI4 handle multi-tenancy?
Answer
Multi-tenancy in CodeIgniter 4 can be implemented using several strategies. Shared database with tenant column: add a tenant_id to all tables. Create a base model that automatically adds WHERE tenant_id = {current_tenant} to all queries via a beforeFind callback. Set the current tenant in a Filter after authenticating the request. Separate schemas/databases per tenant: use dynamic database switching based on the tenant identifier. Configure the database connection in a Filter: $db = \Config\Database::connect(["database" => "tenant_" . $tenantId]). Subdomain routing: identify tenants by subdomain using CI4's subdomain routing and set a tenant context accordingly. The shared database approach is simpler; separate databases provide stronger isolation. In both cases, a Filter or BaseController method is the right place to resolve and set the current tenant context before any controller logic runs.