diff --git a/src/TenantManager.php b/src/TenantManager.php index 4a719ae..c1d16dc 100644 --- a/src/TenantManager.php +++ b/src/TenantManager.php @@ -130,10 +130,6 @@ public function getTenantId($tenant) */ public function applyTenantScopes(Model $model) { - if (!$this->enabled) { - return; - } - if ($this->tenants->isEmpty()) { // No tenants yet, defer scoping to a later stage $this->deferredModels->push($model); @@ -141,13 +137,7 @@ public function applyTenantScopes(Model $model) } $this->modelTenants($model)->each(function ($id, $tenant) use ($model) { - $model->addGlobalScope($tenant, function (Builder $builder) use ($tenant, $id, $model) { - if($this->getTenants()->first() && $this->getTenants()->first() != $id){ - $id = $this->getTenants()->first(); - } - - $builder->where($model->getQualifiedTenant($tenant), '=', $id); - }); + $this->addGlobalScopeToSingleModel($tenant, $id, $model); }); } @@ -163,19 +153,35 @@ public function applyTenantScopesToDeferredModels() $model->setAttribute($tenant, $id); } - $model->addGlobalScope($tenant, function (Builder $builder) use ($tenant, $id, $model) { - if($this->getTenants()->first() && $this->getTenants()->first() != $id){ - $id = $this->getTenants()->first(); - } - - $builder->where($model->getQualifiedTenant($tenant), '=', $id); - }); + $this->addGlobalScopeToSingleModel($tenant, $id, $model); }); }); $this->deferredModels = collect(); } + /** + * Add the global scope to a single model + * + * @param string|Model $tenant_column + * @param string $tenant_id + * @param Model $model + */ + private function addGlobalScopeToSingleModel($tenant_column, $tenant_id, $model) + { + $model->addGlobalScope($tenant_column, function (Builder $builder) use ($tenant_column, $tenant_id, $model) { + if(!$this->enabled) { + return; + } + + if($this->getTenants()->first() && $this->getTenants()->first() != $tenant_id){ + $tenant_id = $this->getTenants()->first(); + } + + $builder->where($model->getQualifiedTenant($tenant_column), '=', $tenant_id); + }); + } + /** * Add tenant columns as needed to a new model instance before it is created. *