From 5bb743f73dc5e7cc0d439bd44b21845d0cc72e5b Mon Sep 17 00:00:00 2001 From: Sean Taylor Date: Sat, 22 Feb 2020 12:58:30 +0000 Subject: [PATCH] Reinitialize tenancy for queued jobs if tenant id has changed (#276) * Reinitialize tenancy for queued jobs if tenant id has changed * Refactor condition logic for better readability --- src/TenancyServiceProvider.php | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/src/TenancyServiceProvider.php b/src/TenancyServiceProvider.php index 604d8a09..b5c41c73 100644 --- a/src/TenancyServiceProvider.php +++ b/src/TenancyServiceProvider.php @@ -109,11 +109,21 @@ class TenancyServiceProvider extends ServiceProvider // Queue tenancy $this->app['events']->listen(\Illuminate\Queue\Events\JobProcessing::class, function ($event) { - if (array_key_exists('tenant_id', $event->job->payload())) { - if (! tenancy()->initialized) { // dispatchNow - tenancy()->initialize(tenancy()->find($event->job->payload()['tenant_id'])); - } + $tenantId = $event->job->payload()['tenant_id'] ?? null; + + // The job is not tenant-aware + if (! $tenantId) { + return; } + + // Tenancy is already initialized for the tenant (e.g. dispatchNow was used) + if (tenancy()->initialized && tenant('id') === $tenantId) { + return; + } + + // Tenancy was either not initialized, or initialized for a different tenant. + // Therefore, we initialize it for the correct tenant. + tenancy()->initById($tenantId); }); } }