Laravel-根据所有调用的条件更新雄辩的模型列

时间:2020-04-15 16:03:10

标签: php laravel eloquent

我有以下laravel雄辩的模型:

名称:区域

字段:id,名称,名称_en

name-我的默认语言名称 name_en-英文名称

我希望每当查询这个雄辩的模型(e.g Zone::find(1))时,它将检查用户使用哪种语言,并将name设置为正确的语言。在这种情况下,如果我的用户语言是en,它将设置名称to name_en`。

目标是以正确的语言返回name属性(如果用户lang为en,则需要name_en,否则为默认的name

我正在寻找的实际上是在我使用区域模型时运行以下代码:

if($ user-> lang_code ==“ en){ $ this-> name = $ this-> name_en; }

当然,我可以更改所有API并执行此操作,但是我正在寻找一种解决方案,将其应用于我在应用程序中使用区域模型的任何位置,而无需手动更改每个位置。

在对Zone模型的每次查询之后,是否有Laravel地方可以执行这样的代码?

2 个答案:

答案 0 :(得分:0)

我建议使用spatie / laravel-translateable软件包 您可以像这样使用它:

$newsItem = new NewsItem; // This is an Eloquent model
$newsItem
->setTranslation('name', 'en', 'Name in English')
->setTranslation('name', 'nl', 'Naam in het Nederlands')
->save();

$newsItem->name; // Returns 'Name in English' given that the current app locale is 'en'
$newsItem->getTranslation('name', 'nl'); // returns 'Naam in het Nederlands'

app()->setLocale('nl');

$newsItem->name; // Returns 'Naam in het Nederlands'  

翻译存储为json。不需要额外的桌子来容纳它们, 您甚至可以设置后备区域设置

https://github.com/spatie/laravel-translatable

答案 1 :(得分:0)

您可以使用Eloquent Accessor进行此操作。

按如下所示在getNameAttribute模型中定义函数Zone

public function getNameAttribute($value)
{
    // get the user's locale
    $locale = Auth::user()->locale;

    // If the user's locale is same as app locale,
    // no changes. Just return the name as it is.
    if ($locale === app()->getLocale()) {
        return $value;
    }
    // If the user has a different locale,
    // check if there is a name matching that locale and return it.
    // If no matching name found, return original name.
    return $this->{'name_'.$locale} ?? $value;
}

现在,每当您访问name模型的zone属性时,此函数都会根据 User locale name >

适用于PHP7.0或更高版本。

此方法支持更多可以在以后添加的语言环境。换句话说,您无需修改​​此功能即可支持新的语言环境。

相关问题