From 17b97d832484b81b0a79dfaa32d41e3f878dd844 Mon Sep 17 00:00:00 2001 From: Sean Taylor Date: Thu, 23 Jan 2020 17:29:57 +0000 Subject: [PATCH 1/2] Reinitialize tenancy for queued jobs if tenant id has changed --- src/TenancyServiceProvider.php | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/TenancyServiceProvider.php b/src/TenancyServiceProvider.php index 604d8a091..5a99231b2 100644 --- a/src/TenancyServiceProvider.php +++ b/src/TenancyServiceProvider.php @@ -109,10 +109,12 @@ public function boot(): void // 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; + if ( + $tenantId !== null && + (! tenancy()->initialized || tenancy('id') !== $tenantId) + ) { + tenancy()->initById($tenantId); } }); } From e3fe37a8492b996ba988e4c14e9d854669499994 Mon Sep 17 00:00:00 2001 From: Sean Taylor Date: Fri, 21 Feb 2020 10:59:18 +0000 Subject: [PATCH 2/2] Refactor condition logic for better readability --- src/TenancyServiceProvider.php | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/src/TenancyServiceProvider.php b/src/TenancyServiceProvider.php index 5a99231b2..b5c41c736 100644 --- a/src/TenancyServiceProvider.php +++ b/src/TenancyServiceProvider.php @@ -110,12 +110,20 @@ public function boot(): void // Queue tenancy $this->app['events']->listen(\Illuminate\Queue\Events\JobProcessing::class, function ($event) { $tenantId = $event->job->payload()['tenant_id'] ?? null; - if ( - $tenantId !== null && - (! tenancy()->initialized || tenancy('id') !== $tenantId) - ) { - tenancy()->initById($tenantId); + + // 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); }); } }