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 simple methods like translateText(), using your DeepL authentication key. Composer install, supports PHP 7.3+ with ongoing updates as the API evolves.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require deeplcom/deepl-php
    

    Ensure PHP ≥8.1 (recommended) or ≥7.3.

  2. Authentication:

    • Obtain a DeepL API key (Free tier: 500K chars/month).
    • Store the key securely (e.g., Laravel .env):
      DEEPL_API_KEY=f63c02c5-f056-...
      
  3. First Translation:

    use DeepL\DeepLClient;
    
    $client = new DeepLClient(config('services.deepl.key'));
    $result = $client->translateText('Hello, world!', null, 'fr');
    echo $result->text; // "Bonjour, le monde !"
    
  4. Configuration: Initialize the client with options (e.g., timeout, proxy):

    $client = new DeepLClient(
        $authKey,
        ['timeout' => 30, 'proxy' => 'http://proxy.example.com']
    );
    

Implementation Patterns

Core Workflows

Text Translation

  • Batch Translation:
    $results = $client->translateText(
        ['Text 1', 'Text 2'],
        null, // Auto-detect source
        'es'
    );
    
  • Contextual Translation:
    $result = $client->translateText(
        'The "user" clicked the button.',
        null,
        'de',
        ['context' => 'User interface terminology']
    );
    

Document Translation

  • Streaming Large Files: Use uploadDocument() + pollDocumentStatus() + downloadDocument() for granular control:
    $handle = $client->uploadDocument('input.docx', 'en');
    $client->pollDocumentStatus($handle->documentId);
    $client->downloadDocument($handle->documentId, 'output.docx');
    

Rephrasing

  • Style/Tone Control:
    $result = $client->rephraseText(
        'This is a draft.',
        'en-US',
        ['writing_style' => 'business']
    );
    

Integration Tips

  1. Laravel Service Provider: Bind the client to the container for dependency injection:

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton(DeepLClient::class, function ($app) {
            return new DeepLClient(config('services.deepl.key'));
        });
    }
    
  2. Queueable Jobs: Offload document translations to queues (avoid timeouts):

    // app/Jobs/TranslateDocumentJob.php
    public function handle()
    {
        $client = app(DeepLClient::class);
        $client->translateDocument('input.docx', 'output.docx', 'en', 'fr');
    }
    
  3. Caching Responses: Cache translated text/document results (e.g., Redis) to avoid API calls for repeated requests:

    $cacheKey = "deepl:translate:{$sourceLang}:{$targetLang}:{$text}";
    $translation = cache()->remember($cacheKey, now()->addHours(1), function () use ($client, $text, $sourceLang, $targetLang) {
        return $client->translateText($text, $sourceLang, $targetLang)->text;
    });
    
  4. Error Handling: Centralize exception handling (e.g., retry logic for rate limits):

    try {
        $result = $client->translateText($text, $source, $target);
    } catch (\DeepL\DeepLException $e) {
        if ($e->getCode() === 429) {
            sleep(1); // Retry after rate limit
            return $this->handle($request);
        }
        throw $e;
    }
    

Gotchas and Tips

Pitfalls

  1. API Key Exposure:

    • Never commit .env or hardcoded keys to version control.
    • Use Laravel’s env() helper or a dedicated config file:
      config('services.deepl.key');
      
  2. Character Billing:

    • DeepL bills by source text characters (not translated output).
    • Check billedCharacters in TextResult to estimate costs:
      $chars = $result->billedCharacters; // e.g., 12 for "¿Cómo estás?"
      
  3. Document Size Limits:

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

    • Free tier: 500K chars/month (reset daily).
    • Pro tier: 1M chars/month (default). Monitor usage via DeepL Dashboard.
    • Handle 429 Too Many Requests with exponential backoff.
  5. Language Pair Availability:

    • Not all language pairs support formality/custom_instructions. Test with:
      $client->getUsage(); // Check available features
      
  6. XML/HTML Tag Handling:

    • tag_handling: 'xml' requires valid XML. Use outline_detection: false for malformed markup:
      $options = [
          'tag_handling' => 'xml',
          'outline_detection' => false,
      ];
      

Debugging

  1. Enable Logging: Configure the client to log API requests/responses:

    $client = new DeepLClient($authKey, [
        'logger' => new \Monolog\Logger('deepl'),
        'logger_level' => \Monolog\Logger::DEBUG,
    ]);
    
  2. Inspect Raw Responses: Access the underlying Guzzle client for debugging:

    $response = $client->getHttpClient()->getLastResponse();
    $body = json_decode($response->getBody(), true);
    
  3. Common Errors:

    • 401 Unauthorized: Invalid API key.
    • 400 Bad Request: Invalid language codes (e.g., 'sp' instead of 'es').
    • 413 Payload Too Large: File exceeds 30MB. Use minification or split into chunks.

Extension Points

  1. Custom Middleware: Add request/response filters:

    $client->getHttpClient()->getEmitter()->attach(
        \GuzzleHttp\Middleware::tap(function ($request) {
            // Modify request (e.g., add headers)
            $request = $request->withHeader('X-Custom-Header', 'value');
            return $request;
        })
    );
    
  2. Model-Specific Logic: Override default model selection (e.g., force latency_optimized):

    $options = [
        'model_type' => 'latency_optimized',
    ];
    $client->translateText($text, $source, $target, $options);
    
  3. Glossary Integration: Pre-load glossaries and reuse IDs:

    $glossaryId = $client->createGlossary('my_glossary', ['term' => 'translation']);
    $client->translateText($text, null, 'fr', ['glossary' => $glossaryId]);
    
  4. Style Rules: Create reusable style rules via the API and reference them:

    $styleId = $client->createStyleRule('business_style', ['formality' => 'more']);
    $client->translateText($text, null, 'de', ['style_id' => $styleId]);
    

Performance Tips

  1. Batch Processing:

    • Translate arrays of text in a single API call (reduces overhead):
      $client->translateText(['text1', 'text2'], null, 'fr');
      
  2. Async Document Handling:

    • Use pollDocumentStatus() in a loop with delays:
      while ($status = $client->pollDocumentStatus($docId)->status !== 'done') {
          sleep(2); // Poll every 2 seconds
      }
      
  3. Memory Management:

    • Stream large document uploads/downloads to avoid memory issues:
      $client->uploadDocument('large.docx', 'en', null, null, null, true); // Stream
      
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport