aegued / laravel-translations
创建模型字段的翻译并将其保存到数据库
v1.03
2024-06-12 09:56 UTC
Requires
- php: >=5.6.4
Requires (Dev)
- phpunit/phpunit: ~5.0
This package is auto-updated.
Last update: 2024-09-12 11:07:58 UTC
README
这是一个Laravel模型列翻译管理器
安装
您可以通过composer安装此包
composer require aegued/laravel-translations
如果您使用的是Laravel 5.5及以上版本,则包将自动注册自己。
否则,您需要在app/config/app.php中添加服务提供者
Aegued\LaravelTranslations\LaravelTranslationsServiceProvider::class,
如果您想更改默认的语言环境,您必须发布配置文件
php artisan vendor:publish --provider="Aegued\LaravelTranslations\LaravelTranslationsServiceProvider"
这是发布文件的包含内容
return [ /** * Default Locale || Root columns locale * We will use this locale if config('app.locale') translation not exist */ 'locale' => 'en', /** * Supported Locales e.g: ['en', 'es', 'fr'] */ 'locales' => ['es', 'en', 'fr'] ];
下一步迁移翻译表
php artisan migrate
使模型可翻译
使模型可翻译所需的步骤包括
- 只需使用
Aegued\LaravelTranslations\Translatable
特质。
以下是一个准备好的模型示例
use Illuminate\Database\Eloquent\Model; use Aegued\LaravelTranslations\Translatable; class Item extends Model { use Translatable; /** * The attributes that are Translatable. * * @var array */ protected $translatable = [ 'name', 'color' ]; }
可用方法
保存翻译
$item = new Item; $data = array('en' => 'car', 'es' => 'coche'); $item->setTranslations('name', $data); // setTranslations($attribute, array $translations, $save = false) // or save one translation $item->setTranslation('name', 'en', 'car', true); // setTranslation($attribute, $locale, $value, $save = false) // or just do $item->name = 'car'; // note: this will save automaticaly unless it's the default locale // This will save if (current locale == default locale OR $save = false) $item->save();
获取翻译
$item = new Item::first(); // get current locale translation $item->city OR $item->getTranslation('city'); // pass translation locales $item->getTranslation('city', 'es'); // getTranslation($attribute, $language = null, $fallback = true) $item->getTranslationsOf('name', ['es', 'en']); // getTranslationsOf($attribute, array $languages = null, $fallback = true)
删除翻译
$item = new Item::first(); $item->deleteTranslations(['name', 'color'], ['es', 'en']); // deleteTranslations(array $attributes, $locales = null)