Getting Started

How it works

A tenant request should never touch another tenant’s database, cache keys, or files. This package keeps that isolation on context.Context: identify who the request belongs to, initialize that tenant on the context, then let bootstrappers switch Laravel services into tenant-scoped mode for the rest of the handler.

Request path (multi-database + domain)

  1. A request hits a route that uses identification middleware (for example ByDomain).
  2. The middleware normalizes the hostname and looks up the tenant on the central database.
  3. On failure, the request is denied (default HTTP 404). Identification is fail-closed unless you deliberately mark a route as universal or omit identification.
  4. On success, Package.Initialize stores the tenant on the context and runs bootstrappers in order.
  5. The database bootstrapper binds a pooled tenant *db.DB with conn.Context(ctx) so default queries use that tenant’s database.
  6. The handler runs fully in the tenant context.
  7. Optional tenancy.End(ctx) reverts bootstrappers (useful in commands and tests). HTTP requests typically rely on request-scoped context ending with the request.

Outside HTTP

Commands, jobs, and tests use the same initialize → work → end loop:

err := pkg.Run(ctx, tenant, func(ctx context.Context) error {
    // tenant-scoped work
    return nil
})

Run calls Initialize, runs your function, then End in a defer.