Skip to content

Commit e6c1d1f

Browse files
Improve tenant scope and team_id handling
1 parent d227864 commit e6c1d1f

File tree

1 file changed

+20
-3
lines changed

1 file changed

+20
-3
lines changed

app/Traits/BelongsToTenant.php

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,36 @@
44

55
use App\Models\Team;
66
use Illuminate\Database\Eloquent\Builder;
7+
use Illuminate\Support\Facades\Schema;
78

89
trait BelongsToTenant
910
{
1011
protected static function booted(): void
1112
{
1213
static::addGlobalScope('team', function (Builder $query): void {
13-
if (auth()->check()) {
14-
$query->where('team_id', static::getTenantId());
14+
// Only apply scope when a tenant is available and the model's table has a team_id column
15+
$tenantId = static::getTenantId();
16+
if (! auth()->check() || empty($tenantId)) {
17+
return;
18+
}
19+
20+
$table = $query->getModel()->getTable();
21+
if (Schema::hasColumn($table, 'team_id')) {
22+
$query->where($table.'.team_id', $tenantId);
1523
}
1624
});
1725

1826
static::creating(function ($model): void {
19-
$model->team_id = static::getTenantId();
27+
// Set team_id on create only if the table has the column and a tenant is present
28+
$tenantId = static::getTenantId();
29+
if (empty($tenantId)) {
30+
return;
31+
}
32+
33+
$table = $model->getTable();
34+
if (Schema::hasColumn($table, 'team_id')) {
35+
$model->team_id = $tenantId;
36+
}
2037
});
2138
}
2239

0 commit comments

Comments
 (0)