tabaoman / laravel-translation
基于Laravel的国际化解决方案
v0.9.4
2020-01-08 08:11 UTC
Requires
- php: ^7.2
- laravel/framework: 5.8.* || ^6.0
README
基于Laravel的国际化解决方案
这是一个用于国际化的Laravel包。您只需创建一个额外的表来管理其他Eloquent实体中的所有多语言文本。
安装
composer require tabaoman/laravel-translation
基本使用
更改新的配置文件 'translation.php'
return [ /* * The table that restores the multi-language texts * NOTES: Avoid to have any timestamp field. * If you need to record the created/updated time, use 'model' as following. */ 'table' => 't_language_translate', /* * An example helper model. * It has a higher priority than 'table' if it is not commented out. */ //'model' => \Tabaoman\Translation\Models\LanguageTranslate::class ];
创建表
注意:如果在使用翻译配置中的 'table',请不要创建带有时间戳字段('create_time', 'update_time')的表。
CREATE TABLE `t_language_translate` ( `id` BIGINT(18) NOT NULL AUTO_INCREMENT, `entity_id` VARCHAR(32) NOT NULL COMMENT 'model id', `lang_code` VARCHAR(18) NOT NULL COMMENT 'language code', `text_code` VARCHAR(18) NOT NULL COMMENT 'text code', `content` LONGTEXT NOT NULL COMMENT 'text', `create_time` DATETIME NOT NULL COMMENT 'created time', `update_time` DATETIME NULL DEFAULT NULL COMMENT 'updated time', PRIMARY KEY (`id`), UNIQUE KEY unique_trans (`entity_id`, `lang_code`, `text_code`) ) COMMENT='i18n table' COLLATE='utf8mb4_general_ci' ENGINE=InnoDB;
在模型类中添加特质和新的成员变量 '$translations'
namespace App\Models; use Illuminate\Database\Eloquent\Model; use Tabaoman\Translation\Translation; class Store extends Model { use Translation; protected $casts = ['id' => 'string']; // Sometimes you need this cast protected $translations = [ 'name' => 'STORE_NAME' // attribute => text code // 'name' => ['code' => 'STORE_NAME'], // Or associate like this // 'name' => ['code' => 'STORE_NAME', 'my_key' => 'my_value'] // You can add custom key-value pair for other uses. ]; // ... }
获取翻译属性
$store = Store::first(); echo $store->name; // Get with default language setting (App::getLocale()) echo $store->getTranslation('name', 'en'); // Get its English name App::setLocale('en'); echo $store->name; // Or get its English name after explicitly set app locale
保存翻译属性
$store = Store::first(); echo $store->name; // 苹果商店 $store->setTranslation('name', 'Apple store', 'en'); // Directly save the English name App::setLocale('en'); $store->name = 'Apple store'; // Or set its English name after explicitly set app locale $store->save(); // Optional if there is no mutator for 'name' $store = Store::first(); echo $store->name; // Apple store App::setLocale('zh_CN'); echo $store->name; // 苹果商店
扁平化i18n属性
在模型类中
protected $translations = [ 'name' => 'STORE_NAME' // attribute => text code 'name_english' => ['code' => 'STORE_NAME', 'locale' => 'en'], // You are free to define your own language code. ];
$store = Store::first(); echo $store->name; // 苹果商店 echo $store->name_english; // Apple store