"HasTranslations" does not work for me
Bekshakx opened this issue · comments
Hello.
Check this other issue: #320 (comment)
@anibalealvarezs Sorry. i wrote a function "getNameAttribute" to the module but not go inside. how to solve this problem?
Hello.
Check documentation about mutators for deep understanding about it: https://laravel.com/docs/8.x/eloquent-mutators#defining-a-mutator
But, simplifying, the magic method should be constructed based on the attribute name. For example:
For title
attribute:
public function getTitleAttribute($value)
{
if ($json = json_decode($value)) {
return $json->{app()->getLocale()} ?? "";
}
return $value;
}
The idea is to format the output for every attribute you have marked as translatable.
======================================================================
If all of the translatable fields are implementing the same method, you can create you own trait with something like:
trait TranslateMethods
{
public function getTranslatedAttribute($value)
{
if ($json = json_decode($value)) {
return $json->{app()->getLocale()} ?? "";
}
return $value;
}
}
And then use the trait in the model and call the method in every mutator:
use [your_namespace]\TranslateMethods;
class NewsArticle extends Model
{
use TranslateMethods;
/* */
public function getTitleAttribute($value)
{
return $this->getTranslatedAttribute($value);
}
public function getTextAttribute($value)
{
return $this->getTranslatedAttribute($value);
}
public function getDescriptionAttribute($value)
{
return $this->getTranslatedAttribute($value);
}
}
Thank you