Skip to content

Commit 105c5be

Browse files
committed
only translate defined attributes
1 parent 06389c3 commit 105c5be

File tree

1 file changed

+40
-13
lines changed

1 file changed

+40
-13
lines changed

src/Traits/TranslatableTrait.php

Lines changed: 40 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,21 @@ trait TranslatableTrait
1111
{
1212
private $cachedModel;
1313

14+
public function __get($key)
15+
{
16+
if ($this->isRelation($key)) {
17+
return $this->getRelationValue($key);
18+
}
19+
20+
// Check if the attribute is translatable
21+
if ($translation = $this->getTranslation($key)) {
22+
return $translation;
23+
}
24+
25+
// Fallback to the default behavior
26+
return parent::__get($key);
27+
}
28+
1429
public function translation(): MorphOne
1530
{
1631
return $this->morphOne(Translation::class, 'translatable');
@@ -21,30 +36,42 @@ public function translations(): MorphMany
2136
return $this->morphMany(Translation::class, 'translatable');
2237
}
2338

24-
public function __get($key)
39+
/**
40+
* Returns translatable attribute(s).
41+
*
42+
* @return null|array|string
43+
*/
44+
protected function getTranslatableAttributes()
2545
{
26-
if ($this->isRelation($key)) {
27-
return $this->getRelationValue($key);
46+
if (defined('static::TRANSLATABLE_ATTRIBUTES')) {
47+
return static::TRANSLATABLE_ATTRIBUTES;
2848
}
2949

30-
// Check if the attribute is translatable
31-
if ($translation = $this->getTranslation($key)) {
32-
return $translation;
50+
return null;
51+
}
52+
53+
private function getTranslation(string $key): ?string
54+
{
55+
if ($this->isTranslatableAttribute($key)) {
56+
$model = $this->getCachedModel();
57+
58+
if ($model instanceof Model) {
59+
return $key == $model->key ? $model->value : null;
60+
}
3361
}
3462

35-
// Fallback to the default behavior
36-
return parent::__get($key);
63+
return null;
3764
}
3865

39-
private function getTranslation($key)
66+
private function isTranslatableAttribute(string $key): bool
4067
{
41-
$model = $this->getCachedModel();
68+
$translatables = $this->getTranslatableAttributes();
4269

43-
if ($model instanceof Model) {
44-
return $key == $model->key ? $model->value : null;
70+
if (is_null($translatables)) {
71+
return true;
4572
}
4673

47-
return null;
74+
return is_array($translatables) ? in_array($key, $translatables) : $key == $translatables;
4875
}
4976

5077
private function getCachedModel()

0 commit comments

Comments
 (0)