Auto-Translating Laravel Language Files with Gemini
The recurring annoyance
In multi-tenant or global web applications, internationalization (i18n) is often a release bottleneck. Every time a backend developer adds a new UI string to lang/en/messages.php, that string must be manually translated into every supported locale (bn, es, fr, de, ar) before shipping.
When manual translation lags behind development sprints, applications either silently fall back to English keys or display raw translation string identifiers (like messages.checkout.tax_breakdown). Existing SaaS translation integrations either require live API calls during HTTP request rendering — introducing external network latency and recurring API costs — or require complex external workflows.
Generate once, cache forever
To solve this, I created laravel-ai-translator. The package hooks into Laravel's native translation event pipeline. When an application requests a key that does not exist in the target locale's language files, the package intercepts the missing key event, routes the string through an NLP translation pipeline powered by the Gemini API (gemini-2.0-flash), and persists the generated translation directly into the target locale's PHP array file on disk.
graph TD
App["Blade View / API Call"] --> Check{"Key Exists in Local PHP File?"}
Check -->|Yes - Fast Path| Cache["Read from Local PHP File<br/>0.01ms memory lookup"]
Check -->|No - First Time| Event["MissingTranslation Event Triggered"]
Event --> Gemini["Gemini 2.0 Flash API Call<br/>Structured JSON Schema"]
Gemini --> Write["Write translated string to disk<br/>lang/bn/messages.php"]
Write --> Cache

Because the generated string is saved to the local filesystem immediately, subsequent calls execute standard PHP array memory lookups. The application incurs zero runtime API latency, zero ongoing API cost per page view, and zero operational dependency on Gemini API availability.
// missing key 'welcome' in lang/bn/messages.php
__('messages.welcome')
// 1. Intercepted by missing-translation event listener
// 2. Translated via Gemini API (e.g., "আমাদের প্ল্যাটফর্মে স্বাগতম")
// 3. Written to lang/bn/messages.php
// 4. Subsequent requests read directly from PHP array in 0.01ms
Gemini API & Structured JSON Schema Architecture
Communicating with Large Language Models for UI copy requires deterministic, machine-readable output. Unstructured text responses often include conversational filler (e.g., "Here is your translation:") that breaks application UI templates.
Using google-gemini-php/laravel, we enforce strict response structure using Gemini's native JSON schema capabilities:
$responseText = Gemini::generativeModel(model: 'gemini-2.0-flash')
->withGenerationConfig(
generationConfig: new GenerationConfig(
maxOutputTokens: 4096,
temperature: 0.3,
responseMimeType: ResponseMimeType::APPLICATION_JSON,
responseSchema: new Schema(
type: DataType::ARRAY,
items: new Schema(
type: DataType::OBJECT,
properties: [
'local' => new Schema(type: DataType::STRING),
'translated' => new Schema(type: DataType::STRING),
],
required: ['local', 'translated']
),
)
)
)
->generateContent($prompt)
->text();
To handle rate limits cleanly, the service catches HTTP 429 and RESOURCE_EXHAUSTED responses via a custom QuotaExceededException, parsing the API's retryAfter duration and applying exponential backoff retries without burning API quota.
NLP Processing: Language Detection & Markdown AST Chunking
Translating arbitrary UI strings and Markdown documentation requires specialized NLP processing:
- ISO 639-1 Language Detection: Automatic 2-letter language code identification (
en,bn,es,fr) for dynamic input strings. - Markdown Front-Matter AST Parsing:
MarkdownTranslationServiceparses Markdown files, separating YAML front-matter metadata from the main content body. Translatable fields (title,lead,description) are batch-translated while technical properties (sort_order,tags,icon) are preserved verbatim. - Heading-Based Section Chunking: To prevent token limit truncation on long-form documentation, Markdown bodies are automatically split across
##level-2 headings. Each section is processed as an isolated NLP chunk before being reassembled. - Placeholder & Markup Integrity: Custom prompt rules and regex sanitizers enforce strict preservation of Laravel
:variable(colon prefix) and{variable}(brace syntax) placeholders, as well as embedded HTML formatting tags (<b>,<i>,<a href="...">).
What kept it honest: Diffable Human Review
The primary concern with automated LLM translation is silent copy mistranslation. To address this, laravel-ai-translator includes a review workflow: newly generated translations are recorded in a diffable log file (lang/vendor/ai-translator/review.json).
Engineers or localization managers can quickly review newly generated strings during pull-request reviews, approving or overriding values before deploying to production environments.
Results
Integrating laravel-ai-translator into application localization workflows delivered significant efficiency gains:
- Batch Efficiency: 35 missing UI keys across 3 target languages were translated in 4 batch API calls during initial staging execution, requiring zero API calls on all subsequent production requests.
- Documentation Parity: Full technical Markdown documentation files are automatically translated into target locales while preserving complex formatting and code blocks.
- Zero Production Risk: Disk-cached PHP language files guarantee that production runtime performance remains completely isolated from third-party API availability.