eugene-erg / laravel-icu-i18n-translate
Laravel integration for eugene-erg/icu-i18n-translator: Eloquent storage, migrations and the Translator in the service container
Package info
github.com/EugeneErg/Laravel-icu-i18n-translate
pkg:composer/eugene-erg/laravel-icu-i18n-translate
Requires
- php: ^8.2
- eugene-erg/icu-i18n-translator: ^4.4
- eugene-erg/json-formatter-icu-i18n-translator: ^1.2
- eugene-erg/laravel-syntax-icu-i18n-translator: ^1.0.1
- eugene-erg/php-array-formatter-icu-i18n-translator: ^1.2
- eugene-erg/sync-icu-i18n-translator: ^1.0
- illuminate/database: ^12.0 || ^13.0
- illuminate/support: ^12.0 || ^13.0
Requires (Dev)
- larastan/larastan: ^3.10
- laravel/pint: ^1.29
- orchestra/testbench: ^10.0 || ^11.1
- phpstan/extension-installer: ^1.4
- phpstan/phpstan: ^2.2
- phpstan/phpstan-deprecation-rules: ^2.0
- phpstan/phpstan-phpunit: ^2.1
- phpstan/phpstan-strict-rules: ^2.1
- phpunit/phpunit: ^12.5
Suggests
None
Provides
None
Conflicts
None
Replaces
None
- dev-main
- 5.0.0
- 4.2.0
- 4.1.2
- 4.1.1
- 4.1.0
- 4.0.0
- 3.0.1
- 3.0.0
- 2.0.0
- 1.0.7
- 1.0.6
- 1.0.5
- 1.0.4
- 1.0.3
- 1.0.2
- 1.0.1
- 1.0.0
- dev-feature/5.0
- dev-feature/laravel-gaps
- dev-chore/shared-workflows
- dev-docs/lang-sync-api
- dev-docs/merging-formatters
- dev-feature/sync-command
- dev-chore/translator-4
- dev-chore/description
- dev-feature/translator-3
- dev-feature/translator-2
This package is auto-updated.
Last update: 2026-12-02 23:48:29 UTC
README
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
- Architecture
- Requirements
- Installation
- Database Setup
- Configuration
- Usage
- Comparison with Laravel's built-in localisation
- Upgrading to 5.x
- Upgrading to 4.x
- Upgrading to 3.x
- Upgrading to 2.x
- Testing
- Contributing
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
| Table | Purpose |
|---|---|
icu_i18n_groups |
One row per unique ICU pattern + context + source locale combination (unique hash + locale) |
icu_i18n_translates |
One row per unique translated pattern per locale |
icu_i18n_group_translates |
Pivot: maps a group variant key to a translated pattern |
icu_i18n_paths |
Hierarchical 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-intlextension (forMessageFormatterand ICU support)php-mbstringextension
Installation
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:
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:
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:
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:
use EugeneErg\IcuI18nTranslator\Translator; $translator = app(Translator::class);
Translating plain text
// 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:
$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:
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:
$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:
// 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:
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}/**/*.phpandlang/{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(phpandjson), which are registered by default with the Laravel syntax. If you bind your own list, keep them in it:
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/:
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:
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
| Feature | Laravel lang/ files |
This package |
|---|---|---|
| Format | PHP arrays / JSON files | ICU Message Format |
| Pluralisation | trans_choice, ` |
` syntax |
| Date/number formatting | Manual | Built-in ICU formatting via php-intl |
| Auto-translation | ✗ | ✔ via pluggable external translators |
| Storage | Files | Database (cached, reusable) |
| Translation caching | None (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/export | N/A | ✔ via FormatterInterface |
| PHP version | 8.1+ | 8.2+ |
| Laravel version | All | 13.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:
php artisan migrate
icu_i18n_paths.valuebecomesTEXT; keys are found by a newvalue_hashcolumn (md5 of the key), unique per parent. Rolling the migration back fails while a key is longer than 255 characters.i18n:syncruns oneugene-erg/sync-icu-i18n-translator:SyncedFile,SyncActionandSyncExceptionmoved fromEugeneErg\LaravelIcuI18nTranslate\SynctoEugeneErg\SyncIcuI18nTranslator, andLangSync::files()returns itsCatalogFiles;LangFileis 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
idcolumn 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:
php artisan migrate
icu_i18n_pathsgets a nullablenotecolumn.- 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 nowimportTranslations($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:
php artisan migrate
localecolumns grow to 35 characters: ICU spellings such aszh_Hant_TWorsr_Latn_RSdid 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.
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
- Fork the repository.
- Create a feature branch.
- Fix one of the known bugs listed above, or add a new feature.
- Add tests that cover the change.
- Run
./vendor/bin/phpunitand./vendor/bin/phpstan analyse— both must pass. - Open a pull request.