Displaying database columns based on current langu

2020-02-06 04:01发布

in database i have this:

name_en | name_fr 

When the user select french language - for example - i want to get name_fr field, and the same thing if he chose another language

1条回答
劳资没心,怎么记你
2楼-- · 2020-02-06 04:45

Assuming you set locale in your application using:

App::setLocale($lang);

if you use Eloquent, you can add to your model class accesssor:

public function getNameAttribute($value) {
    return $this->{'name_'.App::getLocale()};
}

and also mutator:

public function setNameAttribute($value) {
    $this->{'name_'.App::getLocale()} = $value;
}

Assuming you added those functions to Content model you can now use:

$content = Content::first(); // find first article
echo $content->name;  // displaying its name

$content->name = 'updated content'; // changing its name
$content->save(); // saving

This will cause displaying and changing name_{$lang} if you set lang using setLocale

查看更多
登录 后发表回答