stancl / tenancy-docs

stancl/tenancy docs & website
https://tenancyforlaravel.com/docs
MIT License
64 stars 633 forks source link

[4.x] Document UrlTenancyBootstrapper (using tenant URLs in queued emails) #242

Closed lukinovec closed 1 year ago

lukinovec commented 1 year ago

UrlTenancyBootstrapper {#url-tenancy-bootstrapper}

You might want to generate tenant URLs in queued emails or the CLI, but that can't be done automatically because tenants can have many domains – we don't have a way of telling which one to use in the URL when tenancy isn't initialized using the browser.

UrlTenancyBootstrapper allows you to solve that problem by overriding the app's root URL generation in the tenant context using the customizable $rootUrlOverride closure which accepts an instance of Tenant.

After enabling UrlTenancyBootstrapper in your Tenancy config, you can specify the way the URL gets generated by changing the UrlTenancyBootstrapper::$rootUrlOverride closure in your TenancyServiceProvider's overrideUrlInTenantContext() method. For example:

// In TenancyServiceProvider's overrideUrlInTenantContext()
UrlTenancyBootstrapper::$rootUrlOverride = function (Tenant $tenant) {
    $baseUrl = url('/');
    $scheme = str($baseUrl)->before('://');
    $hostname = str($baseUrl)->after($scheme . '://'); // E.g. 'acme.test'

    // url('/') in the context of tenant with the key 'foo' will return 'https://foo.acme.test'
    return $scheme . '://' . $tenant->getTenantKey() . '.' . $hostname;
}

This closure will be used for generating the app's root URL in the tenant context.