Initializing tenancy
Tenancy initialization — the process of transitioning the application into a tenant’s context — always happens by a
tenancy()->initialize()
call:
When tenancy is initialized, the configured tenancy bootstrappers are executed.
This normally happens in middleware on web requests, and in specific queue events when using the QueueTenancyBootstrapper.
That said, you should feel free to manually initialize tenancy anywhere as needed. Simply keep in mind that you should revert to the previous context after you’re done with the logic in a given tenant’s context. Using the callback-based approaches below ensures this is done for you.
Reverting back to the central context
You may revert back to the central context by calling the end()
method:
Running callbacks in the tenant context
You can use the run()
method to run a Closure for a specific tenant:
If your Tenant model uses the TenantRun
trait (or extends our base Tenant
model), you can use:
After these callbacks are executed, the package will automatically revert to the previous context (central/different tenant).
Running callbacks in the central context
Similar to the above, you can use the central()
method to run a callback in the central context:
Events
Under the hood, all of this logic is event-based:
tenancy()->initialize()
dispatchesTenancyInitialized
BootstrapTenancy
listens toTenancyInitialized
BootstrapTenancy
loops through the bootstrappers configured intenancy.bootstrappers
and callsbootstrap($tenant)
on each one
When tenancy is ended:
tenancy()->end()
dispatchesTenancyEnded
RevertToCentralContext
listens toTenancyEnded
RevertToCentralContext
again loops through the bootstrappers but callsrevert()
this time