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)
- A request hits a route that uses identification middleware (for example
ByDomain). - The middleware normalizes the hostname and looks up the tenant on the central database.
- On failure, the request is denied (default HTTP 404). Identification is fail-closed unless you deliberately mark a route as universal or omit identification.
- On success,
Package.Initializestores the tenant on the context and runs bootstrappers in order. - The database bootstrapper binds a pooled tenant
*db.DBwithconn.Context(ctx)so default queries use that tenant’s database. - The handler runs fully in the tenant context.
- 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.