spatie / laravel-translatable

Making Eloquent models translatable

Home Page:https://spatie.be/docs/laravel-translatable

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

"HasTranslations" does not work for me

Bekshakx opened this issue · comments

I want to get only "ru", but it gives me all of this.
image
image

What I expected to happen
app->getLocale('ru);

data : {
"title" : "asssssssssss",
....
}

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?

image
image

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