2013-09-30 70 views
6

我正在Laravel创建一个后端应用程序。后端需要管理下载到应用程序的对象集合。对象必须根据设备语言进行本地化。Laravel多语言数据库管理

在Laravel有没有简单的方法来做到这一点?也许是一个雄辩的或Laravel插件?我想避免自己写本地化支持。

(内置在Laravel定位是只为界面,它不支持雄辩对象)

回答

9

你需要编写你自己的。首先,你将不得不模型数据库表来支持多语言内容,然后在你的模型,你就可以这样说:

class Content extends Eloquent 
{ 

    public function scopeEnglish($query) 
    { 
      return $query->where('language', '=', 'en'); 
    } 

    public function scopeSpanish($query) 
    { 
     return $query->where('language', '=', 'es'); 
    } 
} 


class Post extends Eloquent 
{ 
    public function content() 
    { 
    return $this->hasMany('Content'); 
    } 
} 

,然后你可以使用它像:

$englishContent = Posts::find($id)->content->english()->get(); 
$spanishContent = Posts::find($id)->content->spanish()->get(); 
6

高兴帮助的答案似乎完美的多语言网站与许多语言。 我发现当你的网站只有两种/三种语言时,这样做很笨拙。

我所做的是为每个可翻译字段设置两列。 为title属性我在数据库中有title_entitle_es。 之后,在控制器中只需设置此方法即可进行自动翻译。

public function getTitleAttribute() 
{ 
    $locale = App::getLocale(); 
    $column = "title_" . $locale; 
    return $this->{$column}; 
} 

现在,当您拨打Post::find($id)->title时,它会自动获得当前语言版本。

希望它有帮助。 干杯!

1

继@ @ user1067281答案我发现了一个多语言站点的高级教程。

你应该完全检查了这一点:https://medium.com/laravel-4/26cdc75e4810

+2

请考虑添加解释,而不仅仅是一个链接。 – Onik

+0

对此不了解。感谢提示@Onik –

4

我做了类似的,但更普遍的

Schema::create('index', function(Blueprint $table) { 
     $table->increments('id'); 
     $table->string('title_uk'); 
     $table->string('title_ru'); 
     $table->string('title_en'); 
     $table->string('heading_uk'); 
     $table->string('heading_ru'); 
     $table->string('heading_en'); 
     $table->string('photo'); 
     $table->timestamps(); 
    }); 

模型

public function TextTrans($text) 
{ 
    $locale=App::getLocale(); 
    $column=$text.'_'.$locale; 

    return $this->{$column}; 
} 

现在我各种语言版本以及为每个字段将不会规定具体的功能,并导致所有这一切:

$text=Index::find('1'); $text->TextTrans('title'); $text->TextTrans('heading');