使用Laravel进行多语言数据库管理

Mac*_*wic 6 database multilingual laravel eloquent laravel-4

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

在Laravel有一个简单的方法吗?也许是一个雄辩的或Laravel插件?我想避免自己编写本地化支持.

(Laravel中内置的本地化仅用于界面,它不支持Eloquent对象)

Gla*_*elp 10

您需要自己编写.首先,您必须为数据库表建模以支持多语言内容,然后在您的模型中,您将能够说出如下内容:

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'); 
  }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以使用它像:

$englishContent = Posts::find($id)->content->english()->get();
$spanishContent = Posts::find($id)->content->spanish()->get();
Run Code Online (Sandbox Code Playgroud)


adr*_*dev 7

Glad To Help的答案似乎非常适合多种语言的多语言网站.我发现当你的网站只有两种/三种语言时,这样做很笨拙.

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

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

现在,当你打电话时Post::find($id)->title,它将自动获得当前语言的一个.

希望能帮助到你.干杯!


小智 5

我做了类似但更普遍

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();
    });
Run Code Online (Sandbox Code Playgroud)

该模型

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

    return $this->{$column};
}
Run Code Online (Sandbox Code Playgroud)

现在我为每个语言版本以及每个字段都不会规定特定的功能,并导致所有这些:

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