Getting Started
Getting started
1. Install and register
go get github.com/martinshaw/laravel-go-tenancytenancy.New(func(cfg *tenancy.Config) {
cfg.Drivers = []db.Driver{sqlite.Driver} // or postgres.Driver / mysql.Driver
cfg.CentralDomains = []string{"localhost", "example.com"}
cfg.Identification.SingleDomainTenants = true
cfg.TenantMigrations = tenantMigrations.All
})Config.Drivers must match the drivers listed in Options.Drivers. List every
hostname that serves the central
app in CentralDomains (exact host match; example.com does not block tenant
hosts like acme.example.com).
2. Migrate the central database
laravel migrateThis creates tenants and domains (domains is unused when single-domain mode
is on).
3. Create a tenant
domain := "acme.example.com"
tenant := models.Tenant{ID: "acme", Domain: &domain}
err := tenancy.From(ctx).CreateTenant(ctx, &tenant)With multi-database mode, create automatically provisions a database and runs
TenantMigrations.
On a Laravel Herd site with APP_ENV=local, the package will rewrite
the domain to acme.example.com.test and create a Herd alias when Herd is
available, so redirects that use *tenant.Domain open the real local hostname.
4. Add central and tenant routes
pkg := tenancy.From(r) // or keep the package value from New
pkg.OnCentral(route, func(route *routing.Router) {
route.Get("/", centralHome)
})
route.Middleware(pkg.PreventCentral(), pkg.ByDomain()).Group(func(route *routing.Router) {
route.Get("/", func(r *web.Request) *web.Response {
t, _ := tenancy.TenantFrom(r)
return web.Text(t.ID)
})
})Visit the tenant host (for example http://acme.example.com/ locally, or
http://acme.example.com.test/ under Herd) and you should see acme while
queries hit the tenant database.