space_id === null) { $model->space_id = $model->resolveDefaultSpaceId(); } }); } /** @return BelongsTo */ public function space(): BelongsTo { return $this->belongsTo(Space::class); } /** * Restrict a query to a single space. * * @param Builder $query * @return Builder */ public function scopeForSpace(Builder $query, Space|string $space): Builder { return $query->where($this->getTable().'.space_id', $space instanceof Space ? $space->id : $space); } /** * The space a new row defaults to when none was set explicitly: the current * space of the user that owns the row. Models with a stronger anchor (e.g. a * transaction inheriting its account's space) override this. */ protected function resolveDefaultSpaceId(): ?string { return $this->spaceIdFromUser(); } /** * The current space of the user that owns this row, if any. */ protected function spaceIdFromUser(): ?string { $userId = $this->getAttribute('user_id'); if ($userId === null) { return null; } return User::query()->whereKey($userId)->value('current_space_id'); } }