-
-
Notifications
You must be signed in to change notification settings - Fork 171
Description
Is your feature request related to a problem? Please describe.
When serializing a model that uses Translatable, the translated attributes are not automatically included in the toArray() output.
This causes inconsistency when building APIs or returning JSON responses, since the localized fields (like title, name, etc.) are missing unless they are explicitly accessed or manually merged.
Describe the solution you'd like
It would be great if the Translatable trait automatically merged translated attributes into the model’s array output whenever the translation relation is loaded.
For example, when calling Model::with('translation')->get()->toArray(), the resulting array would include all translated fields from the loaded translation.
This could be implemented directly in the Translatable trait, something like:
public function toArray(): array
{
$array = parent::toArray();
if ($this->relationLoaded('translation') && $this->translation) {
foreach ($this->translatedAttributes as $key) {
$array[$key] = $this->translation->$key ?? null;
}
}
return $array;
}Optionally, this could be controlled by a flag (e.g. $includeTranslationInArray = true) for backward compatibility.
Describe alternatives you've considered
I created a custom extension trait to override toArray():
use Astrotomic\Translatable\Translatable;
trait ExtendedTranslatable
{
use Translatable;
public function toArray(): array
{
$array = $this->attributesToArray();
if ($this->relationLoaded('translation') && $this->translation) {
foreach ($this->translatedAttributes as $key) {
$array[$key] = $this->translation->$key ?? null;
}
}
return array_merge($array, $this->relationsToArray());
}
}While this works, having it built into the package would avoid repeating this pattern across multiple projects.
Additional context
- Laravel: 12.x
- PHP: 8.3
- Package:
astrotomic/laravel-translatable(v11.x) - Use case: API responses and Vue/React front-ends where translated attributes should appear automatically.