目的
實現(xiàn)多語言站點的開發(fā),用戶根據(jù)訪問 /en、/zh-CN 等瀏覽不同語言的站點。
開發(fā)工具
安裝完成上述工具后,進行開發(fā)。
步驟
修改 translatable.php 配置文件
在 translatable.php 文件 locales 中修改站點語言:
'locales' => [
'en',
'zh-CN',
],
修改 RouteServiceProvider.php 文件
public function map(Request $request)
{
$locale = $request->segment(1);
$this->app->setLocale($locale);
$this->mapApiRoutes();
$this->mapWebRoutes($locale);
}
protected function mapWebRoutes($locale)
{
if (in_array($locale, $this->app->config->get('translatable.locales'))) {
Route::group([
'middleware' => 'web',
'prefix' => $locale,
'namespace' => $this->namespace,
], function ($router) {
require base_path('routes/web.php');
});
} else {
Route::group([
'middleware' => 'web',
'namespace' => $this->namespace,
], function ($router) {
require base_path('routes/web.php');
});
}
}
添加語言翻譯包
對于我們站點里的靜態(tài)內(nèi)容,我們可以通過在 resources/lang 下面添加指定語言包,使用 trans('指定名稱') 來進行翻譯,詳情請見 文檔
至此,我們可以通過訪問 /en、/zh-CN 瀏覽指定語言的站點了。但是,我們應(yīng)該發(fā)現(xiàn),對于我們在數(shù)據(jù)庫里讀取的數(shù)據(jù)并沒有發(fā)生改變
創(chuàng)建模型及遷移
現(xiàn)在是 dimsav/laravel-translatable 包大展身手的時候了
模型
// Article 模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Dimsav\Translatable\Translatable;
class Article extends Model
{
use Translatable; // 引入 Translatable Trait(前提安裝dimsav/laravel-translatable)
public $translatedAttributes = ['name', 'text'];
protected $guarded = ['id'];
}
// ArticleTranslation 模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ArticleTranslation extends Model
{
public $timestamps = false;
protected $guarded = ['id'];
}
NOTE: 其中 $translatedAttributes 設(shè)置要翻譯的字段
遷移
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->boolean('online');
$table->timestamps();
});
Schema::create('article_translations', function (Blueprint $table) {
$table->increments('id');
$table->integer('article_id')->unsigned();
$table->string('locale')->index();
$table->string('name');
$table->text('text');
$table->unique(['article_id','locale']);
$table->foreign('article_id')->references('id')->on('articles')->onDelete('cascade');
});
NOTE: 其中 *_translations 表中必須包含對應(yīng)表的關(guān)聯(lián) ID *_id、區(qū)域標識 locale及要翻譯的字段等
其他
在每次創(chuàng)建模型記錄時,使用模型的 translateOrNew() 方法添加翻譯內(nèi)容,如:
$article->translateOrNew('zh-CN')->name = "中文";
在每次讀取模型數(shù)據(jù)時,直接讀取就可以了,其他工作 dimsav/laravel-translatable 包已經(jīng)做了。