Skip to content

Initializing tenancy

Tenancy initialization — the process of transitioning the application into a tenant’s context — always happens by a tenancy()->initialize() call:

tenancy()->initialize($tenant);

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:

tenancy()->end();

Running callbacks in the tenant context

You can use the run() method to run a Closure for a specific tenant:

$usersInTenant = tenancy()->run($tenant, fn () => User::count());

If your Tenant model uses the TenantRun trait (or extends our base Tenant model), you can use:

$usersInTenant = $tenant->run(fn () => User::count());

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:

$centralUsers = tenancy()->central(fn () => User::count());

Events

Under the hood, all of this logic is event-based:

  • tenancy()->initialize() dispatches TenancyInitialized
  • BootstrapTenancy listens to TenancyInitialized
  • BootstrapTenancy loops through the bootstrappers configured in tenancy.bootstrappers and calls bootstrap($tenant) on each one
app/Providers/TenancyServiceProvider.php
Events\TenancyInitialized::class => [
Listeners\BootstrapTenancy::class,
],

When tenancy is ended:

  • tenancy()->end() dispatches TenancyEnded
  • RevertToCentralContext listens to TenancyEnded
  • RevertToCentralContext again loops through the bootstrappers but calls revert() this time
app/Providers/TenancyServiceProvider.php
Events\TenancyEnded::class => [
Listeners\RevertToCentralContext::class,
],