Skip to content

RootUrlBootstrapper

The RootUrlBootstrapper changes the root URL used by Laravel’s URL generator — the base URL that url() and route() use — when tenancy is initialized in CLI context.

When URLs are generated in a web request, they’re based on the request hostname. When they’re generated in a CLI process (like a queue worker or an Artisan command), there’s no request hostname, so Laravel uses the configured app.url. This results in URLs pointing to the central domain even when tenancy is initialized — e.g. in queued mail.

To enable this bootstrapper, uncomment the RootUrlBootstrapper line in the bootstrappers section of the tenancy config:

config/tenancy.php
'bootstrappers' => [
// Bootstrappers\RootUrlBootstrapper::class,
],

The bootstrapper doesn’t do anything until you tell it what root URL to use for each tenant. That’s done by setting the $rootUrlOverride static property to a closure that accepts the tenant and the original root URL, and returns the new root URL.

A simple implementation, using the tenant’s first domain, could look like this:

app/Providers/TenancyServiceProvider.php
protected function overrideUrlInTenantContext(): void
{
RootUrlBootstrapper::$rootUrlOverride = function (Tenant $tenant, string $originalRootUrl) {
return 'https://' . $tenant->domains->first()->domain . '/';
};
}

Your TenancyServiceProvider already has this method with a recommended implementation commented out. It covers most setups without changes — it supports both domain and subdomain identification, single-domain tenants, and tenants without a domain — but you can simplify it or adjust it for your app.

Besides the URL generator’s root URL, the bootstrapper also sets app.url to the new root URL. Both are restored when tenancy is ended.

Since your tests also run in CLI context, the bootstrapper changes the root URL in tests too. If this causes issues in some of your tests, you can disable the behavior in tests:

RootUrlBootstrapper::$rootUrlOverrideInTests = false;

With path identification, the tenant isn’t part of the root URL but part of the route path. To generate tenant-aware URLs in that case, use the UrlGeneratorBootstrapper instead.