Maintenance mode
Laravel’s php artisan down puts the entire application into maintenance mode. Tenancy lets you do the same
for individual tenants, while the rest of the application keeps working.
Enabling tenant maintenance mode
Section titled “Enabling tenant maintenance mode”First, add the MaintenanceMode trait to your tenant model:
namespace App\Models;
use Stancl\Tenancy\Database\Models\Tenant as BaseTenant;use Stancl\Tenancy\Database\Concerns\HasDatabase;use Stancl\Tenancy\Database\Concerns\HasDomains;use Stancl\Tenancy\Database\Concerns\MaintenanceMode;use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
class Tenant extends BaseTenant implements TenantWithDatabase{ use HasDatabase, HasDomains, MaintenanceMode;}Then, add the CheckTenantForMaintenanceMode middleware to your tenant routes. This is the middleware that
actually blocks requests to tenants in maintenance mode. The package doesn’t add it to any routes for you, so
without it, putting a tenant into maintenance mode has no effect on requests.
The middleware needs to know the current tenant, so list it after the identification middleware. Otherwise, maintenance mode may silently have no effect:
Route::middleware([ 'web', Middleware\InitializeTenancyByDomain::class, Middleware\PreventAccessFromUnwantedDomains::class, Middleware\CheckTenantForMaintenanceMode::class, Middleware\ScopeSessions::class,])->group(function () { // ...});On universal routes, requests in the central context (without a tenant) are let through.
Commands
Section titled “Commands”php artisan tenants:down puts tenants into maintenance mode, and php artisan tenants:up takes them out of it.
Both commands run for all tenants by default and accept
tenant options:
php artisan tenants:down # all tenantsphp artisan tenants:down --tenants=foo --tenants=barphp artisan tenants:up --tenants=footenants:down also supports most of the options of Laravel’s down command:
--redirect, --render, --retry, --refresh, --secret, and --status. All of the selected tenants are
put into maintenance mode with the same options. Like with Laravel’s down, --status sets the status code of the
response (503 by default), --retry adds a Retry-After header, and --refresh adds a Refresh header, which makes
browsers reload the page after the given number of seconds.
--with-secret isn’t supported. Use --secret with a key of your choice instead.
Rendering a view
Section titled “Rendering a view”With --render, tenants in maintenance mode respond with the given view, using the maintenance mode status code
(503 by default):
php artisan tenants:down --render=maintenanceLaravel’s down command renders the view once and stores the resulting HTML. Here, the view is rendered on each
request instead, with tenancy initialized, so it can use tenant data, e.g. {{ tenant('name') }}, and always
shows the tenant’s current data. The view also receives a $retryAfter variable with the --retry
value (a number of seconds, or an HTTP date if you passed a date).
Laravel’s error views work too, e.g. --render=errors::503. Like elsewhere in Laravel, this uses your
resources/views/errors/503.blade.php if you have one, and Laravel’s default 503 page otherwise.
If the view can’t be rendered (e.g. it doesn’t exist, or an exception is thrown while rendering it), the exception
is reported and the request gets the default 503 response, as if --render wasn’t used.
Redirecting
Section titled “Redirecting”With --redirect, requests to tenants in maintenance mode are redirected to the given path, e.g.
--redirect=/maintenance. The path isn’t prefixed with the tenant, so this is meant for domain and subdomain
identification (see path identification).
JSON requests
Section titled “JSON requests”Requests that expect JSON (where Laravel’s $request->expectsJson() returns true) aren’t redirected and don’t
get the view. Instead, they get Laravel’s plain JSON error response with the maintenance mode status code (503 by
default), same as with Laravel’s maintenance mode.
Bypassing maintenance mode
Section titled “Bypassing maintenance mode”When you put tenants into maintenance mode with a secret:
$ php artisan tenants:down --secret=letmein INFO Tenant: foo. INFO Tenant: bar. INFO Tenants are now in maintenance mode. INFO You may bypass maintenance mode by adding [?maintenance_secret=letmein] to a tenant URL.You can bypass maintenance mode by visiting any page of the tenant (that uses the CheckTenantForMaintenanceMode
middleware) with the secret in the maintenance_secret query parameter:
https://foo.example.com/dashboard?maintenance_secret=letmeinVisiting a URL like this sets a bypass cookie that’s valid for 12 hours, and redirects to the same URL without the
maintenance_secret parameter (other query parameters are kept). While you have the cookie, the tenant’s pages work
normally.
Bypass cookies are only valid for the secret they were created with. If you put a tenant into maintenance mode again with a different secret, existing bypass cookies stop working for that tenant.
Like the session cookie, the bypass cookie uses the session.domain config. When it’s not set (which is
typical for apps that identify tenants by domain), the cookie only applies to the tenant’s host. If tenants
share a cookie domain, e.g. with session.domain set to .example.com, or with path identification, they
also share the bypass cookie. That’s fine when they have the same secret (e.g. when they were all put into
maintenance mode by the same tenants:down --secret=... run), but with different secrets, bypassing maintenance
mode for one tenant replaces the cookie for the other.
Excluded paths
Section titled “Excluded paths”Paths excluded from Laravel’s maintenance mode, e.g. using preventRequestsDuringMaintenance() in
bootstrap/app.php, are also excluded for tenants:
->withMiddleware(function (Middleware $middleware) { $middleware->preventRequestsDuringMaintenance(except: [ '/health', ]);})tenants:down has no option for excluding paths (neither does Laravel’s down), but you can exclude paths for
specific tenants when putting them into maintenance mode
in code. These are added to the app-wide ones, so a tenant can’t un-exclude a path
that’s excluded for the whole app.
Since the app-wide list applies to tenant requests too, a path you’ve excluded for the central app, e.g. /webhooks,
is also reachable on tenants in maintenance mode. Laravel also matches these entries against the full URL, so to only
exclude the path on your central domain, include the domain: '*://example.com/webhooks'.
With path identification, the paths need to include the tenant segment, see below.
Path identification
Section titled “Path identification”Maintenance mode works with path identification, but a few things don’t take the tenant in the path into account:
--redirectpaths aren’t prefixed with the tenant.--redirect=/maintenancesends users to the central/maintenanceroute, not to/{tenant}/maintenance.- Excluded paths are matched against the full path of the request, so they need
to include the tenant segment, e.g.
*/healthinstead of/health. - All tenants share one bypass cookie, so they should use the same secret.
Putting tenants into maintenance mode in code
Section titled “Putting tenants into maintenance mode in code”The MaintenanceMode trait adds two methods to the tenant model, which the commands use under the hood:
$tenant->putDownForMaintenance([ 'secret' => 'letmein', 'render' => 'maintenance', 'except' => ['/health'],]);
$tenant->bringUpFromMaintenance();putDownForMaintenance() accepts the same values as the options of tenants:down (redirect, render, retry,
refresh, secret, and status), as well as except, an array of paths to exclude for this tenant. The data is
stored in the tenant’s maintenance_mode attribute, so you can check if a tenant is in maintenance mode using
$tenant->maintenance_mode !== null.
Unlike tenants:down, putDownForMaintenance() stores the values as they are. In particular, retry is used
directly as the Retry-After header, so it should be a number of seconds or an HTTP date (tenants:down --retry
converts other date formats for you).
Events
Section titled “Events”putDownForMaintenance() dispatches the TenantMaintenanceModeEnabled event, and bringUpFromMaintenance()
dispatches TenantMaintenanceModeDisabled. Both events have a $tenant property. You can listen to them in
your TenancyServiceProvider, see the event system page.
Deployments
Section titled “Deployments”During a deployment that runs tenant migrations, you can use tenant maintenance mode instead of taking the entire
app down with php artisan down. If nothing else in the deployment requires the whole app to be down (e.g. central
migrations that the old code can’t work with), you can put only the tenants you’re migrating into maintenance mode
and bring each one back up as soon as it’s migrated.
Putting each tenant into maintenance mode only while its own migrations run usually isn’t enough. Once the new code is deployed, tenants that haven’t been migrated yet would be running the new code against the old database schema, which is only safe if the new code also works with that schema. So the order is:
- Put the tenants you’re migrating into maintenance mode
- Deploy the new code
- Migrate the tenants, and bring each one back up as soon as its migrations are done
The first two steps are part of your deployment script. For the last step, you can write a command that migrates the tenants one by one, and brings each one up once its migrations succeed:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;use Illuminate\Support\LazyCollection;use Stancl\Tenancy\Concerns\HasTenantOptions;use Stancl\Tenancy\Concerns\ParallelCommand;
class MigrateTenants extends Command{ use HasTenantOptions, ParallelCommand;
protected $signature = 'app:migrate-tenants';
protected $description = 'Migrate tenants and bring each one up from maintenance mode';
public function __construct() { parent::__construct();
$this->specifyParameters(); // Adds the tenant options $this->addProcessesOption(); }
public function handle(): int { if ($this->getProcesses() > 1) { return $this->runConcurrently($this->getTenantChunks()->map(fn ($chunk) => $this->getTenants($chunk))); }
return $this->migrateTenants($this->getTenants()) ? 0 : 1; }
protected function childHandle(mixed ...$args): bool { return $this->migrateTenants($args[0]); }
protected function migrateTenants(LazyCollection $tenants): bool { $success = true;
foreach ($tenants as $tenant) { $code = $this->call('tenants:migrate', [ '--tenants' => [$tenant->getTenantKey()], '--with-pending' => true, '--skip-failing' => true, ]);
if ($code === 0) { $tenant->bringUpFromMaintenance(); } else { $success = false; } }
return $success; }}The HasTenantOptions and ParallelCommand traits give the command the same
tenant options and --processes (-p) option as
tenants:migrate. With --processes, the tenants are split into chunks, and each chunk is migrated in a forked
process (this requires the pcntl extension).
Then, the deployment script looks like this:
php artisan tenants:down --render=maintenance --retry=60# Deploy the new codephp artisan app:migrate-tenantsA few things to keep in mind:
- A tenant is only brought up if its migrations succeed. Otherwise, it stays in maintenance mode until you fix
the issue and run
tenants:upfor it. Failures that--skip-failinghandles (a missing tenant database or a failing query) don’t stop the other tenants from being migrated. Either way, the command exits with 1, so your deployment script can react to the failure. - The command brings up every tenant it successfully migrates, including tenants that were in maintenance mode for other reasons before the deployment.
- If you only migrate some tenants, pass the same tenant options to
tenants:downandapp:migrate-tenants.
Alternatively, you could listen to the DatabaseMigrated event to take each tenant out of maintenance mode.
If you’d rather bring all tenants up at the end, you don’t need a custom command:
php artisan tenants:down --render=maintenance --retry=60# Deploy the new codephp artisan tenants:migrate && php artisan tenants:upHere, if any tenant’s migrations fail, tenants:up doesn’t run, so all of the tenants stay in maintenance mode.
That said, you don’t need to deploy this way. If your migrations work with both the old and the new code, you may
not need maintenance mode during deployments at all, and php artisan down is a perfectly fine option too. Tenant
maintenance mode is just a tool for when you specifically want to take some tenants down, or when your tenant
migrations do require downtime and you’d like each tenant to be back up as soon as it’s migrated, instead of
waiting for the entire deployment to finish.