Enhance Translation Handling in HasTranslations Trait: Improved the translate method to ensure non-empty values are returned from the translations table and original field values. Added JSON handling for original values to support array-based translations. This update enhances localization support and ensures more reliable translation retrieval across different languages.

This commit is contained in:
Ümit Tunç
2026-01-06 21:42:33 +03:00
parent 3a2661cf95
commit 374d4a8d7d
+23 -8
View File
@@ -42,33 +42,48 @@ trait HasTranslations
{
$languageCode = $languageCode ?? $this->getCurrentLanguageCode();
// 1. Try translations table
$translation = $this->getTranslation($fieldName, $languageCode);
if ($translation) {
if ($translation && !empty($translation->field_value)) {
return $translation->field_value;
}
// Fallback to default language
// 2. Fallback to default language from translations table
if ($fallback && $languageCode !== $this->getDefaultLanguageCode()) {
$defaultTranslation = $this->getTranslation($fieldName, $this->getDefaultLanguageCode());
if ($defaultTranslation) {
if ($defaultTranslation && !empty($defaultTranslation->field_value)) {
return $defaultTranslation->field_value;
}
}
// Fallback to original field value
// 3. Fallback to original field value
$originalValue = $this->{$fieldName} ?? null;
// Handle JSON string if not casted
if (is_string($originalValue) && (str_starts_with($originalValue, '{') || str_starts_with($originalValue, '['))) {
$decoded = json_decode($originalValue, true);
if (json_last_error() === JSON_ERROR_NONE) {
$originalValue = $decoded;
}
}
// If the original value is an array (e.g. JSON cast), try to find translation inside it
if (is_array($originalValue)) {
if (isset($originalValue[$languageCode])) {
if (isset($originalValue[$languageCode]) && !empty($originalValue[$languageCode])) {
return $originalValue[$languageCode];
}
if ($fallback && isset($originalValue[$this->getDefaultLanguageCode()])) {
if ($fallback && isset($originalValue[$this->getDefaultLanguageCode()]) && !empty($originalValue[$this->getDefaultLanguageCode()])) {
return $originalValue[$this->getDefaultLanguageCode()];
}
// Return first value if available, or empty string
return reset($originalValue) ?: '';
// Return first non-empty value if available
foreach ($originalValue as $val) {
if (!empty($val)) {
return $val;
}
}
return '';
}
return $originalValue;