@@ -11,6 +11,21 @@ trait TranslatableTrait
11
11
{
12
12
private $ cachedModel ;
13
13
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
+
14
29
public function translation (): MorphOne
15
30
{
16
31
return $ this ->morphOne (Translation::class, 'translatable ' );
@@ -21,30 +36,42 @@ public function translations(): MorphMany
21
36
return $ this ->morphMany (Translation::class, 'translatable ' );
22
37
}
23
38
24
- public function __get ($ key )
39
+ /**
40
+ * Returns translatable attribute(s).
41
+ *
42
+ * @return null|array|string
43
+ */
44
+ protected function getTranslatableAttributes ()
25
45
{
26
- if ($ this -> isRelation ( $ key )) {
27
- return $ this -> getRelationValue ( $ key ) ;
46
+ if (defined ( ' static::TRANSLATABLE_ATTRIBUTES ' )) {
47
+ return static :: TRANSLATABLE_ATTRIBUTES ;
28
48
}
29
49
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
+ }
33
61
}
34
62
35
- // Fallback to the default behavior
36
- return parent ::__get ($ key );
63
+ return null ;
37
64
}
38
65
39
- private function getTranslation ( $ key )
66
+ private function isTranslatableAttribute ( string $ key ): bool
40
67
{
41
- $ model = $ this ->getCachedModel ();
68
+ $ translatables = $ this ->getTranslatableAttributes ();
42
69
43
- if ($ model instanceof Model ) {
44
- return $ key == $ model -> key ? $ model -> value : null ;
70
+ if (is_null ( $ translatables ) ) {
71
+ return true ;
45
72
}
46
73
47
- return null ;
74
+ return is_array ( $ translatables ) ? in_array ( $ key , $ translatables ) : $ key == $ translatables ;
48
75
}
49
76
50
77
private function getCachedModel ()
0 commit comments