deeplcom/deepl-php
Official PHP client for the DeepL API. Translate text and documents with DeepL’s high-quality machine translation using a simple DeepLClient. Install via Composer, supports PHP 7.3+, and includes configurable options for requests.
composer require deeplcom/deepl-php
$authKey = env('DEEPL_API_KEY'); // Store securely in .env
$client = new \DeepL\DeepLClient($authKey);
$result = $client->translateText('Hello, world!', 'en', 'fr');
echo $result->text; // Outputs: "Bonjour, le monde !"
DeepLClient class: Central interface for all API calls.TextResult/DocumentTranslationException: Response handling patterns.Translate a user-submitted string in a Laravel controller:
use DeepL\DeepLClient;
public function translate(Request $request)
{
$client = new DeepLClient(config('services.deepl.key'));
$result = $client->translateText($request->input('text'), 'auto', 'es');
return response()->json(['translated' => $result->text]);
}
Text Translation
$result = $client->translateText('Text', 'en', 'fr');
$results = $client->translateText(['Text1', 'Text2'], 'auto', 'de');
$options = ['formality' => 'more', 'tag_handling' => 'html'];
$result = $client->translateText('Text', 'en', 'de', $options);
Rephrasing
$result = $client->rephraseText('Original text', 'en-US', ['writing_style' => 'business']);
Document Handling
$client->translateDocument('input.docx', 'output.docx', 'en', 'fr');
$handle = $client->uploadDocument('input.docx', 'en');
$client->pollDocumentTranslation($handle, 'fr');
$client->downloadDocument($handle, 'output.docx');
Service Provider Bind the client to Laravel’s container:
public function register()
{
$this->app->singleton(DeepLClient::class, function ($app) {
return new DeepLClient(config('services.deepl.key'));
});
}
Config File
// config/services.php
'deepl' => [
'key' => env('DEEPL_API_KEY'),
'default_lang' => 'en',
],
Middleware for Auto-Translation
public function handle($request, Closure $next)
{
$request->merge([
'translated_text' => app(DeepLClient::class)
->translateText($request->text, 'auto', config('services.deepl.default_lang'))
->text
]);
return $next($request);
}
Jobs for Async Document Processing
use DeepL\DeepLClient;
use Illuminate\Bus\Queueable;
class TranslateDocumentJob implements ShouldQueue
{
use Queueable;
public function handle(DeepLClient $client)
{
$client->translateDocument('input.docx', 'output.docx', 'en', 'fr');
}
}
Caching Responses Use Laravel’s cache to avoid redundant API calls:
$cacheKey = "deepl:{$text}:{$targetLang}";
$result = cache()->remember($cacheKey, now()->addHours(1), function () use ($client, $text, $targetLang) {
return $client->translateText($text, 'auto', $targetLang);
});
API Key Exposure
.env or hardcode keys. Use Laravel’s .env and config().config/services.php:
'deepl' => [
'key' => env('DEEPL_API_KEY', throw new RuntimeException('DeepL API key not set.')),
],
Character Limits
billedCharacters in TextResult.if ($result->billedCharacters > 1000) {
Log::warning("High character usage: {$result->billedCharacters}");
}
Document Size Limits
minification for large PPTX files:
$client->translateDocument('large.pptx', 'output.pptx', 'en', 'fr', ['minification' => true]);
Rate Limiting
try {
$result = $client->translateText($text, 'en', 'fr');
} catch (\DeepL\RateLimitException $e) {
sleep(2 ** $e->getRetryAfter());
retry();
}
Language Code Mismatches
$validLangs = ['en', 'fr', 'de', 'es', 'it', 'pt', 'nl'];
if (!in_array(strtolower($targetLang), $validLangs)) {
throw new InvalidArgumentException("Unsupported language: {$targetLang}");
}
Async Document Polling
pollDocumentTranslation() blocks until completion. For Laravel, use queues:
$handle = $client->uploadDocument('input.docx', 'en');
TranslateDocumentJob::dispatch($client, $handle, 'fr')->onQueue('deepl');
Enable Verbose Logging Configure the client to log raw API responses:
$client = new DeepLClient($authKey, [
'logger' => function ($message) {
Log::debug('DeepL API', ['message' => $message]);
}
]);
Handle Exceptions Gracefully Catch specific exceptions:
try {
$result = $client->translateText($text, 'en', 'fr');
} catch (\DeepL\AuthenticationException $e) {
// Handle invalid key
} catch (\DeepL\InvalidUsageException $e) {
// Handle invalid input (e.g., unsupported language)
}
Test with Mock API Calls Use Laravel’s HTTP mocking for unit tests:
$mock = Mockery::mock('overload', \DeepL\DeepLClient::class);
$mock->shouldReceive('translateText')
->once()
->andReturn(new \DeepL\TextResult('Mocked translation', 'en', 10));
Custom Response Transformers
Extend TextResult or create a decorator:
class EnhancedTextResult extends \DeepL\TextResult
{
public function getFormattedText(): string
{
return ucfirst($this->text);
}
}
Batch Processing with Laravel Collections Process arrays of texts efficiently:
$texts = ['Hello', 'World'];
$results = collect($texts)->map(function ($text) use ($client) {
return $client->translateText($text, 'auto', 'fr');
});
Webhook Integration Use DeepL’s webhooks for document translation completion:
Route::post('/deepl-webhook', function (Request $request) {
$client->handleWebhook($request->input());
});
Fallback Mechanisms Implement fallback to another service if DeepL fails:
try {
return $client->translateText($text, 'en', 'fr');
} catch (\Exception $e) {
return app(FallbackTranslator::class)->translate($text, 'fr');
}
Dynamic Glossary/Style Loading Load glossaries or styles from a database:
$glossaryId = DB::table('glossaries')->where('language_pair', 'en
How can I help you explore Laravel packages today?