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 Steps

  1. Installation:

    composer require deeplcom/deepl-php
    

    Ensure your project uses PHP 8.1+ (recommended) or at least PHP 7.3.

  2. Authentication:

    • Obtain an API key from DeepL Pro Account.
    • Store it securely (e.g., Laravel .env file):
      DEEPL_AUTH_KEY=f63c02c5-f056-...
      
  3. First Translation:

    use DeepL\DeepLClient;
    
    $client = new DeepLClient(config('deepl.auth_key'));
    $result = $client->translateText('Hello, world!', 'en', 'fr');
    echo $result->text; // Output: "Bonjour, le monde !"
    

First Use Case: Dynamic Multilingual Content

  • Translate user-generated content (e.g., comments, reviews) in real-time:
    $translations = $client->translateText(
        ['Bonjour!', 'Hola!'],
        null, // Auto-detect source
        'en'
    );
    

Implementation Patterns

Core Workflows

1. Text Translation

  • Batch Processing:
    $texts = ['Text 1', 'Text 2'];
    $results = $client->translateText($texts, 'en', 'es');
    
  • Advanced Options:
    $options = [
        'formality' => 'more',
        'preserve_formatting' => true,
        'custom_instructions' => ['Translate idioms literally.'],
    ];
    $result = $client->translateText('Hello!', 'en', 'de', $options);
    

2. Document Translation

  • Laravel Filesystem Integration:
    use Illuminate\Support\Facades\Storage;
    
    $sourcePath = storage_path('documents/manual.docx');
    $targetPath = storage_path('documents/manual_de.docx');
    
    $client->translateDocument($sourcePath, $targetPath, 'en', 'de');
    

3. Rephrasing

  • Tone/Style Adjustment:
    $result = $client->rephraseText(
        'This is urgent.',
        'en-US',
        ['tone' => 'diplomatic']
    );
    

4. Error Handling

  • Graceful Fallbacks:
    try {
        $result = $client->translateText('...', 'en', 'fr');
    } catch (\DeepL\DeepLException $e) {
        Log::error('DeepL Error: ' . $e->getMessage());
        return back()->with('error', 'Translation failed. Using fallback.');
    }
    

Integration Tips

Laravel-Specific Patterns

  1. Service Provider Binding:

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton(DeepLClient::class, function ($app) {
            return new DeepLClient(config('deepl.auth_key'));
        });
    }
    
  2. API Resource Responses:

    // app/Http/Controllers/TranslationController.php
    public function translate(Request $request)
    {
        $text = $request->input('text');
        $result = app(DeepLClient::class)->translateText($text, 'en', 'fr');
        return response()->json(['translated' => $result->text]);
    }
    
  3. Caching Translations:

    $cacheKey = "translation_{$text}_{$targetLang}";
    $translation = Cache::remember($cacheKey, now()->addHours(1), function () use ($text, $targetLang) {
        return app(DeepLClient::class)->translateText($text, null, $targetLang)->text;
    });
    
  4. Queueing Long-Running Tasks (e.g., document translation):

    // app/Jobs/TranslateDocumentJob.php
    public function handle()
    {
        $client = new DeepLClient(config('deepl.auth_key'));
        $client->translateDocument($this->sourcePath, $this->targetPath, 'en', 'de');
    }
    

Gotchas and Tips

Pitfalls

  1. API Key Exposure:

    • Never commit .env or hardcode keys. Use Laravel's config() or environment variables.
    • Fix: Validate keys in config/deepl.php:
      'auth_key' => env('DEEPL_AUTH_KEY', throw new RuntimeException('DeepL key not set.')),
      
  2. Character Limits:

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

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

    • DeepL enforces 1,000 requests/minute (Pro tier). Implement retries with exponential backoff:
      use Symfony\Component\Process\Exception\TimeoutException;
      
      try {
          $result = $client->translateText(...);
      } catch (\DeepL\RateLimitException $e) {
          sleep(10); // Wait 10 seconds
          retry();
      }
      
  5. Language Pair Availability:

    • Not all combinations support formality or custom_instructions. Check DeepL’s docs first.
    • Fix: Fallback to default:
      $options = ['formality' => 'more'];
      if (!$client->isLanguagePairSupported('en', 'de', $options)) {
          unset($options['formality']);
      }
      
  6. XML/HTML Tag Handling:

    • tag_handling requires careful configuration. Test with simple inputs first:
      $options = [
          'tag_handling' => 'html',
          'tag_handling_version' => 'v2',
      ];
      

Debugging Tips

  1. Enable Verbose Logging:

    $client = new DeepLClient($authKey, [
        'verbose' => true,
        'logger' => new \Monolog\Logger('deepl'),
    ]);
    
  2. Inspect Raw API Responses:

    • Extend the client to log raw responses:
      $client->getHttpClient()->setHandler(new \GuzzleHttp\HandlerStack([
          new \GuzzleHttp\Middleware::tap(function ($request, $next) {
              Log::debug('DeepL Request:', [$request->getUri(), $request->getBody()]);
              return $next($request);
          }),
      ]));
      
  3. Handle Document Translation Errors:

    • Use DocumentTranslationException to clean up partial uploads:
      try {
          $client->translateDocument($source, $target, 'en', 'de');
      } catch (\DeepL\DocumentTranslationException $e) {
          if ($e->documentHandle) {
              $client->deleteDocument($e->documentHandle->documentId);
          }
      }
      

Extension Points

  1. Custom Response Transformers:

    • Extend DeepLClient to format responses for your API:
      class CustomDeepLClient extends DeepLClient
      {
          public function translateAndFormat($text, $targetLang)
          {
              $result = parent::translateText($text, null, $targetLang);
              return [
                  'translation' => $result->text,
                  'source_lang' => $result->detectedSourceLang,
                  'meta' => [
                      'characters' => $result->billedCharacters,
                      'model' => $result->modelTypeUsed,
                  ],
              ];
          }
      }
      
  2. Batch Processing Middleware:

    • Add pre/post-processing for batches:
      $client->translateText($batch, null, 'fr', [
          'preprocess' => function ($text) {
              return str_replace(['...', '...'], '', $text); // Clean text
          },
          'postprocess' => function ($result) {
              return strtoupper($result->text); // Capitalize
          },
      ]);
      
  3. Translation Memory Integration:

    • Use translation_memory_id to enforce brand consistency:
      $options = [
          'translation_memory_id' => 'your_memory_id',
          'translation_memory_threshold' => 85,
      ];
      
  4. Fallback Mechanisms:

    • Combine with other APIs (e.g., Google Trans
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.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai