Skip to content

nxmad/eloquent-i18n

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Eloquent-i18n

Internationalization helper for Eloquent models.

Installation

  1. Pull the latest version using composer:
    composer require nxmad/eloquent-i18n
  2. Publish database migration:
    php artisan vendor:publish --provider="Nxmad\EloquentI18n\EloquentI18nProvider"
  3. 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. }

About

Internationalization of Eloquent Models

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages