Download the PHP package minhyung/laravel-translator without Composer
On this page you can find all versions of the php package minhyung/laravel-translator. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download minhyung/laravel-translator
More information about minhyung/laravel-translator
Files in minhyung/laravel-translator
Package laravel-translator
Short Description Unified translation services (DeepL, Google Cloud Translation, ...) for Laravel.
License MIT
Informations about the package laravel-translator
laravel-translator
English | 한국어
A Laravel package that puts multiple translation services (DeepL, Google Cloud Translation, LLMs, ...) behind one unified API.
You define named translators in config, each picking an implementation with a driver key, and select one with Translator::via('name'). Result caching is built in.
Built-in drivers:
deepl— DeepLgoogle— Google Cloud Translation (v2 by default; v3/Advanced viaversion)claude— native Anthropic Messages API via mozex/anthropic-phpopenai— OpenAI and any OpenAI-compatible endpoint (DeepSeek, Gemini, Groq, Mistral, xAI, OpenRouter, Ollama, self-hosted gateways) via openai-php/client, pointed withbase_urlazure— Azure AI Translator (Translator REST API v3.0)amazon— Amazon Translate via aws/aws-sdk-php (optional dependency)libretranslate— LibreTranslate (free/open-source, self-hosted or hosted)fallback— try several translators in order
No heavyweight LLM abstraction layer — each driver talks to its provider's SDK/API directly.
Requirements
- PHP
^8.3 - Laravel 12 / 13 (
illuminate/support: ^12.0|^13.0)
The Google driver defaults to Translation API v2, which works with an API key alone — no service-account credentials or the
ext-grpcPECL extension required. v3 (Advanced) is opt-in via'version' => 3and authenticates with a service account / Application Default Credentials (REST only — still no gRPC).
Installation
Publish the config file (optional):
Configuration
In config/translator.php or your .env:
Defining translators
Each entry under translators is a named instance whose driver picks the implementation.
Several names may share one driver — e.g. DeepSeek and Gemini both use the openai driver with their own base_url:
For the openai driver, options accepts temperature, max_tokens, system_prompt, and extra_body (arbitrary top-level request-body fields merged into the call, like the OpenAI SDK's extra_body — used above to turn off DeepSeek's thinking mode).
Common base_urls for the openai driver: DeepSeek https://api.deepseek.com/v1, Gemini https://generativelanguage.googleapis.com/v1beta/openai, Groq https://api.groq.com/openai/v1, Mistral https://api.mistral.ai/v1, xAI https://api.x.ai/v1, OpenRouter https://openrouter.ai/api/v1, Ollama http://localhost:11434/v1.
The libretranslate driver takes a base_url (defaults to https://libretranslate.com) and an optional key — only keyed instances need one:
The google driver stays google for both API versions — pick with version. v2 (default) takes an API key; v3 (Advanced) takes a project_id (and optional location) and authenticates with a service account or Application Default Credentials:
The azure driver takes a subscription key. A region is required for regional and multi-service resources (global/single-service keys may omit it); override endpoint for sovereign clouds:
The amazon driver needs the AWS SDK — composer require aws/aws-sdk-php — and a region. Omit key/secret to use the AWS default credential chain (env vars, ~/.aws, IAM instance/task role, ...):
Usage
Single translation
Specify the source language and pass options:
Batch translation (keys and order preserved)
For LLM drivers (
claude,openai), batch translation requests a single JSON object with one in-order result per input and throws if the counts don't match.deepl,azure, andlibretranslatetranslate batches natively;amazon(whose real-time API is one text per call) loops, always preserving order and keys.
Into several languages at once
Selecting a translator
Building a translator at runtime
Need a translator that isn't in your config — e.g. per-tenant credentials? Build one on the fly from an inline config array (same shape as a config entry). The result is a normal Translator (uncached):
Pass a second argument to name it (used on the result's ->translator and in events).
Dependency injection
The Contracts\Translator contract is bound to the default translator.
Language detection
Drivers that can detect a language — google (v2 and v3), azure, and libretranslate — expose detect():
Detection flows through caching, retries, and fallback like translation does. Calling detect() on a translator whose driver can't detect (e.g. deepl, openai) throws a clear error.
Supported languages
Drivers that can enumerate their languages — deepl, google (v2 and v3), azure, amazon, and libretranslate — expose languages():
Glossaries
Glossaries (DeepL) and custom terminologies (Amazon Translate) are named sets of
source → target term overrides. Drivers that can manage them — deepl and
amazon — expose a single, unified API:
Apply a glossary to a translation with the portable glossary option — it maps
to DeepL's glossary id and to Amazon's TerminologyNames:
Management flows through caching and retries like translation does. Calling these
on a translator whose driver can't manage glossaries (e.g. google, azure,
openai) throws a clear error.
Reading entries from
amazondownloads the terminology file Amazon returns, so that translator needs the HTTP client (wired automatically by the package).
Command line
Translate a string straight from the terminal:
Options: --from (source language, auto-detected when omitted), --via (translator name, the default when omitted), --json (output the full result as JSON).
Translate your localization files (PHP groups and the JSON file) into other locales, preserving array structure, :placeholder tokens, and pluralization (apple|apples, {1} :count …). By default only missing keys are filled, so it's safe to re-run:
Options: --source (source locale, default en), --via (translator), --overwrite (re-translate keys that already exist).
Check that your configuration is sound — each translator is built and validated (missing keys/models, unknown fallback children, an undefined default, ...) and reported in a table:
It exits non-zero when something is misconfigured, so it works in CI.
Caching
When translator.cache.enabled is on, every driver is wrapped in a CachingDriver.
Identical inputs (text · source/target language · options) are served straight from the Laravel cache, cutting API calls and cost.
For batch translation, only the cache misses are sent to the provider in a single call.
Retries
Any translator can shrug off transient provider errors (timeouts, 429/5xx) by adding a retry key — an attempt count, or ['times' => , 'sleep' => ] (sleep is the base backoff in ms, multiplied by the attempt number):
Retries sit inside caching (a cache hit never retries) and apply per translator — including each child of a fallback, so a provider self-heals before the chain moves on.
Failover
To automatically switch to the next provider when one fails, define a translator with the fallback driver.
It tries each listed translator in order and moves on to the next whenever one throws.
- Each child translator is cached individually (the
fallbackitself is not cached, to avoid double caching). Every fallback attempt is logged atwarninglevel via a PSR logger and dispatches aTranslationFellBackevent. - If every translator fails, an
AllTranslationDriversFailedExceptionis thrown; usegetErrors()to get the underlying exception per translator.
Queued translation
Translate in the background instead of inline with queue() / queueBatch(). Each dispatches a TranslateJob onto the queue:
The job re-resolves the translator by name on the worker, so it always uses the current config and caching/retry wrapping. Because the work runs in the background, results are delivered through the lifecycle events rather than returned — listen for TranslationCompleted / BatchTranslationCompleted to act on them. TranslationFailed is dispatched once the queue has exhausted the job's retries (from the job's tries or the worker's --tries), not on every failed attempt, so it reflects the ultimate failure.
The job's connection, queue, tries, and backoff come from the translator.queue config — point translations at a dedicated queue/connection there. In tests, fake the queue and assert what was pushed:
Events
The package dispatches lifecycle events you can listen for:
| Event | When |
|---|---|
Events\TranslationCompleted |
a single translate() succeeded (->translator, ->text, ->result, ->sourceLang, ->options) |
Events\BatchTranslationCompleted |
a translateBatch() succeeded (->translator, ->texts, ->results, ->targetLang, ...) |
Events\TranslationFailed |
a request ultimately failed (->translator, ->exception, ->texts, ...) |
Events\TranslationFellBack |
a fallback child threw and the chain moved on (->translator, ->exception) |
Architecture
There are two layers:
Contracts\Driver— the low-level provider contract. Each provider is an adapter implementing it (DeeplDriver,OpenAiDriver, ...), as are the compositeCachingDriverandFallbackDriver.Translator(implementsContracts\Translator) — the public object the manager hands back fromvia()and binds for injection. It wraps aDriverand delegates to it, exposing->driver()and->name().
So Translator::via('claude') returns a Translator wrapping a (cache-wrapped) ClaudeDriver.
Extending with a custom driver
Implement Contracts\Driver and register it on the manager. The callback receives ($container, $name, $config) and returns a Driver; reference it from config with 'driver' => 'papago'.
Testing
In your application's tests, call Translator::fake() so no real provider is hit. It records every translation and returns canned results — by default it echoes the source text; pass a map or a closure to control the output:
Translator::fake() swaps the manager in the container, so the facade, Translator::via()/build(), and an injected Contracts\Translator all record through the fake.
Contributing
License
MIT
All versions of laravel-translator with dependencies
deeplcom/deepl-php Version ^1.19
google/auth Version ^1.52
guzzlehttp/guzzle Version ^7.0
illuminate/bus Version ^12.0|^13.0
illuminate/contracts Version ^12.0|^13.0
illuminate/http Version ^12.0|^13.0
illuminate/queue Version ^12.0|^13.0
illuminate/support Version ^12.0|^13.0
mozex/anthropic-php Version ^1.7
openai-php/client Version ^0.20.0
psr/log Version ^3.0