nxmad / eloquent-i18n
Eloquent模型的国际化
0.1.2
2020-02-17 21:12 UTC
Requires
- php: ^7.0
- laravel/framework: ~5.0 || ~6.0
This package is auto-updated.
Last update: 2024-09-18 07:35:41 UTC
README
Eloquent模型的国际化助手。
安装
- 使用composer拉取最新版本
composer require nxmad/eloquent-i18n
- 发布数据库迁移
php artisan vendor:publish --provider="Nxmad\EloquentI18n\EloquentI18nProvider" - 在模型中使用特性
use Nxmad\EloquentI18n\Traits\HasTranslations; class Something extends Model { use HasTranslations; // ... }
使用指南
添加翻译
$translations = [ 'title' => [ 'en' => 'Hello, world!', 'de' => 'Hallo Welt!', ], 'content' => [ 'en' => 'This is my page content.', 'de' => 'Dies ist mein Seiteninhalt.', ] ]; $page = new Page(); // First way $page->translations = $translations; // Alt. way $page->addTranslations($translations); $page->addTranslations('title', 'Hello, world!'); // would add translation for current locale $page->addTranslations('title', 'Hello, world!', 'en'); // would add translation for specified locale $page->save();
移除翻译
// Remove all existing translations $page->removeTranslations(); // Remove by the key $page->removeTranslations('title'); // Remove by locale $page->removeTranslations(null, 'de'); // Or both: $page->removeTranslations('title', 'de');
获取翻译值
app()->setLocale('de'); echo $page->title; // Hallo Welt! app()->setLocale('en'); echo $page->title; // Hello, world! // alt. way $page->getTranslation('title', 'default', 'en'); // Hello, world! $page->getTranslation('non-existing-key', 'default', 'en'); // default // get all translations for key $page->getAllTranslations('title'); // serialize echo $page->toJson(); // { id, title, content, etc. }