By default, when a model is serialized via toArray(), translatable attributes are returned as JSON strings (the raw database format). If you want toArray() to return the translation for the current locale instead of the JSON object, you can create a custom trait that wraps Spatie\Translatable\HasTranslations and overrides the toArray() method.
This approach ensures that whenever the model is converted to an array (e.g., when returning a model from a controller in an API response), the translatable fields are automatically populated with the value for the current application locale.
namespace App\
Traits;
use Spatie\Translatable\HasTranslations as BaseHasTranslations;
trait HasTranslations
{
use BaseHasTranslations;
public function toArray()
{
$attributes = $this->attributesToArray(); // attributes selected by the query
// remove attributes if they are not selected
$translatables = array_filter($this->getTranslatableAttributes(), function ($key) use ($attributes) {
return array_key_exists($key, $attributes);
});
foreach ($translatables as $field) {
$attributes[$field] = $this->getTranslation($field, \App::getLocale());
}
return array_merge($attributes, $this->relationsToArray());
}
}