Skip to content

Laravel ICU i18n Translate ​

A Laravel package that wires eugene-erg/icu-i18n-translator into a standard Laravel application, providing Eloquent-backed repositories, auto-registered database migrations, and a pre-configured service container binding.


Table of Contents ​


Overview ​

This package provides the Laravel-specific persistence layer (Eloquent models + repositories) for the eugene-erg/icu-i18n-translator core library. The core library understands ICU Message Format patterns and can route translation requests through pluggable external translators (e.g. DeepL, Google Translate, GPT) and formatters (e.g. JSON, YAML localisation files). This package stores the results in your app's database so every translated string is cached and reused on subsequent requests.

Key features ​

  • Full ICU Message Format support: plurals, genders, selects, date/number formatting.
  • Database-cached translations — the external translator API is called at most once per unique string per locale.
  • Optional source-language detection when the original locale is unknown.
  • File-path tree for organising translation keys the same way as traditional lang/ files.
  • Auto-discoverable via Laravel's package discovery — zero config for the ServiceProvider.

Architecture ​

Your Application
       │
       ▼
  Translator (core: eugene-erg/icu-i18n-translator)
  ├── ICU Message Format Parser
  ├── TranslatorInterface[]       ← you implement these (DeepL, GPT, etc.)
  ├── FormatterInterface[]        ← you implement these (JSON, YAML, etc.)
  └── Repository interfaces
            │
            ▼
  This Package (laravel-icu-i18n-translate)
  ├── Eloquent Models
  │   ├── GroupModel        (icu_i18n_groups)
  │   ├── TranslateModel    (icu_i18n_translates)
  │   ├── GroupTranslateModel (icu_i18n_group_translates)
  │   └── PathModel         (icu_i18n_paths)
  └── Repositories (Read/Write) implementing the core interfaces

Database schema ​

TablePurpose
icu_i18n_groupsOne row per unique ICU pattern + context + source locale combination (unique hash + locale)
icu_i18n_translatesOne row per unique translated pattern per locale
icu_i18n_group_translatesPivot: maps a group variant key to a translated pattern
icu_i18n_pathsHierarchical key tree for file-based translation organisation; note keeps what a file explains about a message to a translator

Requirements ​

  • PHP 8.2+
  • Laravel 12 or 13
  • php-intl extension (for MessageFormatter and ICU support)
  • php-mbstring extension

Installation ​

bash
composer require eugene-erg/laravel-icu-i18n-translate

Laravel's package auto-discovery registers the ServiceProvider automatically. No entry in config/app.php is needed.


Database Setup ​

Run the included migrations to create the four tables:

bash
php artisan migrate

The package loads its own migrations via $this->loadMigrationsFrom(...) in the service provider, so the migration files don't need to be published to your database/migrations folder.

To keep the translator's tables in a database of their own, name its connection before migrating:

dotenv
ICU_I18N_DB_CONNECTION=translations   # config('icu-i18n.connection'); the default connection when empty

The migrations and the models use that connection.


Configuration ​

The service provider binds Translator into the container, with two lists you can override in your own service provider:

php
use EugeneErg\IcuI18nTranslator\FormatterInterface;
use EugeneErg\IcuI18nTranslator\TranslatorInterface;

// providers, tried in order — empty by default. Text translators (TranslatorInterface) and providers of
// whole messages (MessageTranslatorInterface: language models) go in the same list
$this->app->singleton(TranslatorInterface::class . '[]', fn () => [
    app(MyLlmTranslator::class),   // whole messages first
    app(MyDeepLTranslator::class),
]);

// file formats — by default 'php' (lang/en/*.php) and 'json' (lang/en.json) with the Laravel syntax,
// so `:name` and `apple|apples` stay as Laravel writes them
$this->app->singleton(FormatterInterface::class . '[]', fn () => [
    'php' => new PhpArrayFormatter(new LaravelSyntax()),
    'json' => new JsonFormatter(new LaravelSyntax()),
    'xlf' => new XliffFormatter(),   // eugene-erg/xliff-formatter-icu-i18n-translator
]);

config/icu-i18n.php (php artisan vendor:publish --tag=icu-i18n-config) holds the settings of i18n:sync and the database connection.


Usage ​

Resolve the Translator class from the container wherever you need it:

php
use EugeneErg\IcuI18nTranslator\Translator;

$translator = app(Translator::class);

Translating plain text ​

php
// Translate "Hello world" from English to French.
// The external translator is called on the first request; the result is cached.
$result = $translator->translateText(
    text: 'Hello world',
    toLocale: 'fr',
    fromLocale: 'en',
);
// → "Bonjour le monde"

// Auto-detect the source language (requires a TranslatorInterface that supports detection)
$result = $translator->translateText(
    text: 'Hello world',
    toLocale: 'de',
);

Translating ICU messages ​

ICU Message Format lets you embed pluralisation, date formatting, and conditional logic directly in your strings:

php
$pattern = '{count, plural, one {# unread message} other {# unread messages}}';

$result = $translator->translateMessage(
    pattern: $pattern,
    values: ['count' => 3],
    toLocale: 'fr',
    fromLocale: 'en',
);
// → "3 messages non lus"

The translator understands which "case" applies for the given values, looks up or creates only the necessary database entries, and returns the formatted string.

Adding an external AI/neural translator ​

Implement TranslatorInterface from the core package:

php
use EugeneErg\IcuI18nTranslator\TranslatorInterface;
use EugeneErg\IcuI18nTranslator\DataTransferObjects\Variable;
use EugeneErg\IcuI18nTranslator\ValueObjects\Translated;

class DeepLTranslator implements TranslatorInterface
{
    public function canTranslate(string $toLocale, ?string $fromLocale = null): bool
    {
        return in_array($toLocale, ['fr', 'de', 'es', 'ja']);
    }

    /**
     * $pattern is an array of strings and Variable placeholders.
     * Translate only the string segments; pass Variable objects through unchanged.
     */
    public function translate(array $pattern, string $fromLocale, string $toLocale, ?string $context = null): array
    {
        return array_map(function ($part) use ($fromLocale, $toLocale) {
            if ($part instanceof Variable) {
                return $part; // Never translate placeholders
            }
            return DeepLApi::translate($part, $fromLocale, $toLocale);
        }, $pattern);
    }

    public function translateWithDetect(array $pattern, string $toLocale, ?string $context = null): Translated
    {
        $detectedLocale = 'en'; // returned by DeepL's detect API
        $translated = $this->translate($pattern, $detectedLocale, $toLocale);
        return new Translated($detectedLocale, $translated);
    }
}

Then register it:

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

Language models translate whole ICU messages (MessageTranslatorInterface): take eugene-erg/llm-icu-i18n-translator or eugene-erg/claude-icu-i18n-translator and put the LlmTranslator in the same list, before the text translators.

Working with files and formatters ​

The Translator can import and export translation files in any format you provide a formatter for:

php
// Import the source file
$translator->addFile(
    format: 'json',
    name: 'messages',
    content: file_get_contents(lang_path('en.json')),
    locale: 'en',
);

// Import translations you already have
$translator->importTranslations('json', 'messages', file_get_contents(lang_path('fr.json')), 'fr');

// Export the file in another language (missing translations are made by the providers)
file_put_contents(lang_path('de.json'), $translator->getFile('json', 'messages', 'de'));

Ready formats are packages: JSON, PHP arrays (lang/*/*.php, parsed, never executed), YAML, Android strings.xml. See the core README for the list and for writing your own FormatterInterface.

Translating lang/ with i18n:sync ​

php artisan i18n:sync writes lang/ in every configured language from its source language:

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 --locale=fr      # only these
php artisan i18n:sync --dry-run                    # which files would be written; translates nothing
php artisan i18n:sync --show-machine               # list the keys a provider translated
  • The source files are lang/{source}/**/*.php and lang/{source}.json; lang/vendor/ is left alone.
  • A missing file is created. An existing one is read first: what a person wrote there is kept and never sent to a provider again; only missing texts are translated. The file is written over itself: comments, key order and layout stay, keys the source no longer has are removed (php-array and json formatters 1.2+; an older formatter writes the file anew, keeping its texts but not its comments and layout).
  • Every file says how many of its texts a provider made: PHP arrays have no place for a "needs review" mark, so review them before you commit. A text you correct in the file becomes manual on the next run; to approve texts as they are, import the file yourself: importTranslations('php', 'lang/messages.php', $content, 'ru').
  • The command uses the formatters named in icu-i18n.formats (php and json), which are registered by default with the Laravel syntax. If you bind your own list, keep them in it:
php
use EugeneErg\JsonFormatterIcuI18nTranslator\JsonFormatter;
use EugeneErg\LaravelSyntaxIcuI18nTranslator\LaravelSyntax;
use EugeneErg\PhpArrayFormatterIcuI18nTranslator\PhpArrayFormatter;

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

The command is a thin wrapper for scripts and CI; the work is done by LangSync, which code can call itself. It is eugene-erg/sync-icu-i18n-translator set up for lang/:

php
use EugeneErg\LaravelIcuI18nTranslate\Sync\LangSync;

foreach (app(LangSync::class)->sync('en', ['ru', 'de']) as $file) {   // dryRun: true to only plan
    // $file->path, $file->action (SyncAction::Created|Updated|Unchanged), $file->machineKeys
}

SyncedFile, SyncAction and SyncException are the sync package's (EugeneErg\SyncIcuI18nTranslator\…).

Machine translations a person checked are approved in code, with the core's $translator->approveMachineTranslations($groupId, 'ru') (translator 4.2).

Managing translations manually ​

You can read, update, or delete translations without going through the external API:

php
use EugeneErg\IcuI18nTranslator\ValueObjects\GroupId;

// List groups (paginated, page 1, 20 per page)
$groups = $translator->getGroups(pageSize: 20, page: 1);

// Read all translation variants for a group in a given locale
$variants = $translator->getTranslates(new GroupId('42'), 'fr');
// Returns array<string, DataTransferObjects\Translate> keyed by variant key ('0', '1', etc.)

// Manually set a translation variant
$translator->setTranslate(new GroupId('42'), key: '0', locale: 'fr', pattern: 'Bonjour');

// Remove a variant from a group
$translator->deleteTranslateFromGroup(new GroupId('42'), key: '0', locale: 'fr');

Comparison with Laravel's built-in localisation ​

FeatureLaravel lang/ filesThis package
FormatPHP arrays / JSON filesICU Message Format
Pluralisationtrans_choice, `` syntax
Date/number formattingManualBuilt-in ICU formatting via php-intl
Auto-translation✗✔ via pluggable external translators
StorageFilesDatabase (cached, reusable)
Translation cachingNone (files always read)DB cache — external API called once per string
Source language detection✗✔ (requires a detector-capable driver)
Context-aware translation✗✔ via context parameter
File import/exportN/A✔ via FormatterInterface
PHP version8.1+8.2+
Laravel versionAll13.3+

Use this package when you need machine translation, ICU-standard plural rules (especially for non-European languages), or want to manage translations from a database/admin UI. Stick with Laravel's built-in system when you manage translations manually through source-controlled files.


Upgrading to 5.x ​

Version 5 lets a key be longer than 255 characters (a key of lang/*.json is a whole sentence) and runs on PostgreSQL, MySQL and MariaDB as on SQLite. Run the migrations:

bash
php artisan migrate
  • icu_i18n_paths.value becomes TEXT; keys are found by a new value_hash column (md5 of the key), unique per parent. Rolling the migration back fails while a key is longer than 255 characters.
  • i18n:sync runs on eugene-erg/sync-icu-i18n-translator: SyncedFile, SyncAction and SyncException moved from EugeneErg\LaravelIcuI18nTranslate\Sync to EugeneErg\SyncIcuI18nTranslator, and LangSync::files() returns its CatalogFiles; LangFile is gone. The files, their names in the translator and the output of the command stay the same.
  • Fixed: a fresh install on MySQL or MariaDB failed on the paths index (an expression index MySQL does not take in that form), and storing a translation link on PostgreSQL asked for an id column the links table does not have.

Upgrading to 4.x ​

Version 4 uses the translator 4: a file can say more about a message than its text. A context (PO msgctxt) tells apart the same text, and a note for translators (PO #., XLIFF <note>, a String Catalog comment) is kept with the key and given to language-model providers. Run the migrations:

bash
php artisan migrate
  • icu_i18n_paths gets a nullable note column.
  • Your own formatters wrap their messages in Message; see the core's Upgrading to 4.x.
  • Update the formatter packages together with this one: their versions for the translator 4 are json, php-array, yaml 1.1, xliff and xcstrings 1.2, po 1.1, android 2.2.

Upgrading to 3.x ​

Version 3 uses the translator 3: formats get a TranslationFile (a file can hold several languages, as XLIFF and PO do) and parse messages with a MessageSyntaxInterface. There are no new migrations.

  • addFile(..., asTranslation: true) is now importTranslations($format, $name, $content, $locale).
  • getFile($format, $name, ...$locales): the locale is positional, locale: is no longer a named argument.
  • Your own formatters implement the new FormatterInterface; see the core's Upgrading to 3.x.

Upgrading to 2.x ​

Version 2 uses eugene-erg/icu-i18n-translator 2 (plural form slots, translation import, machine/manual translations, batch translation, locale normalization). Run the migrations:

bash
php artisan migrate
  • locale columns grow to 35 characters: ICU spellings such as zh_Hant_TW or sr_Latn_RS did not fit into 8.
  • A group is unique per text, context and locale: the same text may be a message in several source languages (before, the second one failed on the unique index).
  • Stored locales are rewritten to the spelling the translator uses now (en-US → en_US, EN → en). Rows that become duplicates are merged into the oldest one; when both merged groups have a translation for the same key and language, the one of the oldest group is kept.

No code changes are needed in your application unless you implemented the translator interfaces yourself: ReadTranslateRepositoryInterface has a new method groupLinksByKey() (implemented here), and Translator::addFile() now returns an ImportResult.

Also fixed in this version: getFiles() listed every path instead of the files only, and getGroups()/getFiles() pages had no stable order.


Testing ​

The package ships with a feature test suite that covers the repositories, the migrations and i18n:sync against an SQLite in-memory database using Orchestra Testbench; CI runs it on PostgreSQL, MySQL and MariaDB too.

bash
composer install
composer check      # pint --test + phpstan (level max, larastan, strict rules) + phpunit
DB_TEST_URL=pgsql://user:password@127.0.0.1:5432/db vendor/bin/phpunit   # on a server (mysql://, mariadb://)

The database a server URL names is wiped by the tests. To add your own tests, extend Tests\Feature\RepositoryTestCase, which configures the database and runs the package migrations.


Contributing ​

  1. Fork the repository.
  2. Create a feature branch.
  3. Fix one of the known bugs listed above, or add a new feature.
  4. Add tests that cover the change.
  5. Run ./vendor/bin/phpunit and ./vendor/bin/phpstan analyse — both must pass.
  6. Open a pull request.

From the readme.md of EugeneErg/laravel-icu-i18n-translate · composer require eugene-erg/laravel-icu-i18n-translate