Skip to content

Commit

Permalink
Handle null values in database columns as null in translations
Browse files Browse the repository at this point in the history
- Updated the HasTranslations trait to return null for translations when the underlying database attribute is null.
- Adjusted the logic in getTranslation to check if the raw attribute value is null before attempting to resolve translations.
- Modified a test case to validate that null database values are treated as null in translations instead of empty strings.
  • Loading branch information
alipadron authored and freekmurze committed Jan 31, 2025
1 parent 4509548 commit 2bf4dcd
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/HasTranslations.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ public function getTranslation(string $key, string $locale, bool $useFallbackLoc

$translations = $this->getTranslations($key);

$translation = $translations[$normalizedLocale] ?? '';
$translation = is_null(self::getAttributeFromArray($key)) ? null : $translations[$normalizedLocale] ?? '';

$translatableConfig = app(Translatable::class);

Expand Down
4 changes: 2 additions & 2 deletions tests/TranslatableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -854,7 +854,7 @@ public function setAttributesExternally(array $attributes)
[['en' => 'english', 'nl' => 'dutch'], ['en', 'nl'], ['english', 'dutch']],
]);

it('should return empty string when the underlying attribute in database is null', function () {
it('should return null when the underlying attribute in database is null', function () {
// we need to remove the name attribute from the translatable array
// and add it back to make sure the name
// attribute is holding `null` raw value
Expand All @@ -864,7 +864,7 @@ public function setAttributesExternally(array $attributes)

$translation = $this->testModel->getTranslation('name', 'en');

expect($translation)->toBe('');
expect($translation)->toBeNull();
});

it('should return locales with empty string translations when allowEmptyStringForTranslation is true', function () {
Expand Down

0 comments on commit 2bf4dcd

Please sign in to comment.