|null */ protected ?array $auditEvents = null; public function disableAuditing(): void { $this->auditEvents = []; } /** * The organization that owns the audited model. * The audits of the model are deleted (via foreign key cascade) when the organization is deleted. */ public function getAuditOwnerOrganizationId(): ?string { if ($this instanceof AuditableThroughParent) { $relation = $this->getAuditParentRelation(); $parentId = $this->getAttributes()[$relation->getForeignKeyName()] ?? null; if ($parentId === null) { return null; } // Note: The loaded parent is only used if it still matches the foreign key and was loaded with the organization $relationName = $relation->getRelationName(); if ($this->relationLoaded($relationName)) { $parent = $this->getRelation($relationName); if ($parent instanceof Model && $parent->getAttribute($relation->getOwnerKeyName()) === $parentId && array_key_exists('organization_id', $parent->getAttributes())) { /** @var string|null $organizationId */ $organizationId = $parent->getAttributes()['organization_id']; return $organizationId; } } /** @var string|null $organizationId */ $organizationId = $relation->getRelated()->newQuery() ->toBase() ->where($relation->getOwnerKeyName(), $parentId) ->value('organization_id'); return $organizationId; } return $this->getAttributes()['organization_id'] ?? null; } /** * The user that owns the audited model. * The audits of the model are deleted (via foreign key cascade) when the user is deleted. */ public function getAuditOwnerUserId(): ?string { return null; } /** * Models that are the owner of their own audits can not record the deletion audit, * since the audit would reference the already deleted model and therefore violate the foreign key. */ protected function isAuditOwnerOfItself(): bool { return false; } /** * @return array */ public function getAuditEvents(): array { $events = $this->auditEvents ?? Config::get('audit.events', [ 'created', 'updated', 'deleted', 'restored', ]); if ($this->isAuditOwnerOfItself()) { $events = array_filter($events, fn (string $value, int|string $key): bool => (is_int($key) ? $value : $key) !== 'deleted', ARRAY_FILTER_USE_BOTH); } return $events; } /** * @param array $data * @return array */ public function transformAudit(array $data): array { $data['owner_organization_id'] = $this->getAuditOwnerOrganizationId(); $data['owner_user_id'] = $this->getAuditOwnerUserId(); return $data; } }