Skip to content

Laravel ​

laravel-icu-i18n-translate stores the translator's data in your database with Eloquent and binds Translator in the container.

bash
composer require eugene-erg/laravel-icu-i18n-translate
php artisan migrate

For a free provider to start with, add laravel-google-informal-icu-i18n-translate: it registers Google Translate as a provider, no key needed.

Providers and formats ​

Register them in a service provider of your app:

php
use EugeneErg\IcuI18nTranslator\FormatterInterface;
use EugeneErg\IcuI18nTranslator\TranslatorInterface;
use EugeneErg\JsonFormatterIcuI18nTranslator\JsonFormatter;
use EugeneErg\LaravelSyntaxIcuI18nTranslator\LaravelSyntax;
use EugeneErg\PhpArrayFormatterIcuI18nTranslator\PhpArrayFormatter;

$this->app->singleton(TranslatorInterface::class . '[]', fn () => [app(MyProvider::class)]);

$this->app->singleton(FormatterInterface::class . '[]', fn () => [
    'php' => new PhpArrayFormatter(new LaravelSyntax()),   // lang/en/*.php
    'json' => new JsonFormatter(new LaravelSyntax()),      // lang/en.json
]);

LaravelSyntax keeps Laravel's :name placeholders and apple|apples plurals as they are in your files.

Translating lang/ ​

bash
php artisan vendor:publish --tag=icu-i18n-config   # config/icu-i18n.php: source, locales, formats
php artisan i18n:sync                              # every language of icu-i18n.locales
php artisan i18n:sync --locale=de --dry-run        # what would be written
php artisan i18n:sync --show-machine               # which keys a provider translated
  • The source is lang/{source}/**/*.php and lang/{source}.json; lang/vendor/ is left alone.
  • A missing file is created; an existing one is read first, so what a person wrote there is kept and only the missing texts are translated.
  • Files are written over themselves: comments, key order and layout stay.
  • PHP and JSON files cannot mark machine translations: review them before you commit. A text you correct in the file becomes a person's on the next run.

The command is a wrapper of LangSync, which your code can call too:

php
use EugeneErg\LaravelIcuI18nTranslate\Sync\LangSync;

foreach (app(LangSync::class)->sync('en', ['ru', 'de']) as $file) {
    // $file->path, $file->action, $file->machineKeys
}

Messages at runtime ​

php
$translator = app(\EugeneErg\IcuI18nTranslator\Translator::class);

$translator->translateMessage('{count, plural, one {# file} other {# files}}', ['count' => 3], 'ru', 'en');
// translated once, then read from the database