Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Disable tenant scope in closure #81

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 24 additions & 18 deletions src/TenantManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -130,24 +130,14 @@ 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);
return;
}

$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);
});
}

Expand All @@ -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.
*
Expand Down