Internationalization helper for Eloquent models.
- Pull the latest version using composer:
composer require nxmad/eloquent-i18n
- Publish database migration:
php artisan vendor:publish --provider="Nxmad\EloquentI18n\EloquentI18nProvider"
- Use trait in your models:
use Nxmad\EloquentI18n\Traits\HasTranslations; class Something extends Model { use HasTranslations; // ... }
Add translations:
$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 translations:
// 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');
Get translated value:
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. }