nxmad / eloquent-i18n
Internationalization of Eloquent Models
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-05-18 06:40:29 UTC
README
Internationalization helper for Eloquent models.
Installation
- 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; // ... }
Usage guide
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. }