File tree Expand file tree Collapse file tree 2 files changed +65
-0
lines changed
tests/Unit/JsonTranslatable Expand file tree Collapse file tree 2 files changed +65
-0
lines changed Original file line number Diff line number Diff line change @@ -255,4 +255,44 @@ public function fill(array $attributes): static
255255
256256 return parent ::fill ($ attributes );
257257 }
258+
259+ /**
260+ * Get the value of an attribute using its mutator for array conversion.
261+ *
262+ * @param string $key
263+ */
264+ protected function mutateAttributeForArray ($ key , $ value )
265+ {
266+ // check if is a suffixed attribute
267+ [$ field , $ locale ] = $ this ->getFieldAndLocale ($ key );
268+
269+ if ($ locale && $ this ->isTranslatable ($ field )) {
270+ return $ this ->{$ key };
271+ }
272+
273+ return parent ::mutateAttributeForArray ($ key , $ value );
274+ }
275+
276+ public function attributesToArray ()
277+ {
278+ $ attributes = parent ::attributesToArray ();
279+
280+ return $ this ->addTranslatableAttributesToArray ($ attributes );
281+ }
282+
283+ /**
284+ * Add the translatable attributes to the attributes array.
285+ */
286+ protected function addTranslatableAttributesToArray (array $ attributes ): array
287+ {
288+ foreach ($ this ->getTranslatables () as $ key ) {
289+ if ( ! isset ($ attributes [$ key ])) {
290+ continue ;
291+ }
292+
293+ $ attributes [$ key ] = $ this ->translate ($ key );
294+ }
295+
296+ return $ attributes ;
297+ }
258298}
Original file line number Diff line number Diff line change @@ -612,4 +612,29 @@ public function it_fills_translatable_and_non_translatable_attributes()
612612 $ this ->assertEquals ('Test Body ' , $ article ->body );
613613 $ this ->assertEquals ('test-title ' , $ article ->slug );
614614 }
615+
616+ #[Test]
617+ public function it_gives_current_locale_language_as_attribute_values ()
618+ {
619+ $ article = new Article ();
620+ $ article ->fill ([
621+ 'title ' => 'Dhivehi Title ' ,
622+ 'body ' => 'Test Body ' ,
623+ 'slug ' => 'dhivehi-title ' ,
624+ 'lang ' => 'dv ' ,
625+ 'translations ' => [
626+ 'en ' => [
627+ 'title ' => 'English Title ' ,
628+ ],
629+ ],
630+ ]);
631+
632+ Languages::setCurrentLocale ('dv ' );
633+ $ attributes = $ article ->toArray ();
634+ $ this ->assertEquals ('Dhivehi Title ' , $ attributes ['title ' ]);
635+
636+ Languages::setCurrentLocale ('en ' );
637+ $ attributes = $ article ->toArray ();
638+ $ this ->assertEquals ('English Title ' , $ attributes ['title ' ]);
639+ }
615640}
You can’t perform that action at this time.
0 commit comments