Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Deepl Php Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:
    composer require deeplcom/deepl-php
    
  2. Authenticate:
    $authKey = env('DEEPL_API_KEY'); // Store securely in .env
    $client = new \DeepL\DeepLClient($authKey);
    
  3. First Translation:
    $result = $client->translateText('Hello, world!', 'en', 'fr');
    echo $result->text; // Outputs: "Bonjour, le monde !"
    

Where to Look First

  • README.md: Covers core usage (translation, rephrasing, documents).
  • DeepLClient class: Central interface for all API calls.
  • TextResult/DocumentTranslationException: Response handling patterns.

First Use Case

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]);
}

Implementation Patterns

Core Workflows

  1. Text Translation

    • Single Text:
      $result = $client->translateText('Text', 'en', 'fr');
      
    • Batch Translation:
      $results = $client->translateText(['Text1', 'Text2'], 'auto', 'de');
      
    • Options:
      $options = ['formality' => 'more', 'tag_handling' => 'html'];
      $result = $client->translateText('Text', 'en', 'de', $options);
      
  2. Rephrasing

    $result = $client->rephraseText('Original text', 'en-US', ['writing_style' => 'business']);
    
  3. Document Handling

    • High-Level:
      $client->translateDocument('input.docx', 'output.docx', 'en', 'fr');
      
    • Low-Level (for async workflows):
      $handle = $client->uploadDocument('input.docx', 'en');
      $client->pollDocumentTranslation($handle, 'fr');
      $client->downloadDocument($handle, 'output.docx');
      

Laravel Integration Tips

  1. 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'));
        });
    }
    
  2. Config File

    // config/services.php
    'deepl' => [
        'key' => env('DEEPL_API_KEY'),
        'default_lang' => 'en',
    ],
    
  3. 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);
    }
    
  4. 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');
        }
    }
    
  5. 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);
    });
    

Gotchas and Tips

Pitfalls

  1. API Key Exposure

    • Never commit .env or hardcode keys. Use Laravel’s .env and config().
    • Fix: Validate keys in config/services.php:
      'deepl' => [
          'key' => env('DEEPL_API_KEY', throw new RuntimeException('DeepL API key not set.')),
      ],
      
  2. Character Limits

    • Free tier: 500,000 characters/month. Track usage via billedCharacters in TextResult.
    • Fix: Log and alert on approaching limits:
      if ($result->billedCharacters > 1000) {
          Log::warning("High character usage: {$result->billedCharacters}");
      }
      
  3. Document Size Limits

    • Max 30MB for most formats. Use minification for large PPTX files:
      $client->translateDocument('large.pptx', 'output.pptx', 'en', 'fr', ['minification' => true]);
      
  4. Rate Limiting

    • DeepL enforces rate limits (e.g., 1,500 requests/minute for Pro).
    • Fix: Implement exponential backoff in custom client wrapper:
      try {
          $result = $client->translateText($text, 'en', 'fr');
      } catch (\DeepL\RateLimitException $e) {
          sleep(2 ** $e->getRetryAfter());
          retry();
      }
      
  5. Language Code Mismatches

    • Case-insensitive but validate against DeepL’s supported languages.
    • Fix: Use a whitelist:
      $validLangs = ['en', 'fr', 'de', 'es', 'it', 'pt', 'nl'];
      if (!in_array(strtolower($targetLang), $validLangs)) {
          throw new InvalidArgumentException("Unsupported language: {$targetLang}");
      }
      
  6. Async Document Polling

    • pollDocumentTranslation() blocks until completion. For Laravel, use queues:
      $handle = $client->uploadDocument('input.docx', 'en');
      TranslateDocumentJob::dispatch($client, $handle, 'fr')->onQueue('deepl');
      

Debugging Tips

  1. Enable Verbose Logging Configure the client to log raw API responses:

    $client = new DeepLClient($authKey, [
        'logger' => function ($message) {
            Log::debug('DeepL API', ['message' => $message]);
        }
    ]);
    
  2. 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)
    }
    
  3. 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));
    

Extension Points

  1. Custom Response Transformers Extend TextResult or create a decorator:

    class EnhancedTextResult extends \DeepL\TextResult
    {
        public function getFormattedText(): string
        {
            return ucfirst($this->text);
        }
    }
    
  2. 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');
    });
    
  3. Webhook Integration Use DeepL’s webhooks for document translation completion:

    Route::post('/deepl-webhook', function (Request $request) {
        $client->handleWebhook($request->input());
    });
    
  4. 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');
    }
    
  5. Dynamic Glossary/Style Loading Load glossaries or styles from a database:

    $glossaryId = DB::table('glossaries')->where('language_pair', 'en
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata