mergeFillable(['tenant_id']); } public static function bootBelongsToTenant(): void { static::addGlobalScope('tenant', function (Builder $builder): void { $context = app(TenantContext::class); if ($context->id() !== null) { $builder->where($builder->getModel()->qualifyColumn('tenant_id'), $context->id()); return; } if ($context->isRequired()) { throw new TenantContextMissing($builder->getModel()::class); } }); static::creating(function (Model $model): void { $inherited = self::tenantIdFromParent($model); if ($inherited !== null) { $model->setAttribute('tenant_id', $inherited); return; } if (filled($model->getAttribute('tenant_id'))) { return; } $current = app(TenantContext::class)->id(); if ($current !== null) { $model->setAttribute('tenant_id', $current); return; } if (app()->runningUnitTests() && ! app(TenantContext::class)->isRequired()) { $model->setAttribute('tenant_id', Tenant::query()->create([ 'name' => 'Testmandant', 'slug' => 'test-'.Str::lower(Str::random(10)), ])->id); return; } throw new TenantContextMissing($model::class); }); } /** * @return BelongsTo */ public function tenant(): BelongsTo { return $this->belongsTo(Tenant::class); } /** * The parent row wins, so a booking cannot land on a different landlord than its apartment. */ private static function tenantIdFromParent(Model $model): ?int { $parents = [ 'property_id' => Property::class, 'booking_id' => Booking::class, 'channel_id' => Channel::class, 'site_id' => Site::class, 'guest_id' => Guest::class, ]; foreach ($parents as $column => $class) { $id = $model->getAttribute($column); if (! $id) { continue; } $tenantId = $class::withoutGlobalScope('tenant')->whereKey($id)->value('tenant_id'); if ($tenantId !== null) { return (int) $tenantId; } } return null; } }