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

Cloud Translate Laravel Package

google/cloud-translate

Idiomatic PHP client for Google Cloud Translation. Supports V2 (handwritten) and V3 (generated) APIs to translate text, detect language, and manage datasets/models. Auth via Google Cloud credentials; install with Composer for easy integration.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    composer require google/cloud-translate
    
  2. Configure authentication (see Google Cloud PHP Auth Guide):
    • Use a service account key (JSON) for local/dev:
      putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/key.json');
      
    • For production, set the environment variable in your Laravel .env:
      GOOGLE_APPLICATION_CREDENTIALS=/path/to/production-key.json
      
  3. First translation (basic text):
    use Google\Cloud\Translate\V3\TranslationServiceClient;
    
    $client = new TranslationServiceClient();
    $response = $client->translateText(
        'Hello, world!',
        ['targetLanguageCode' => 'es']
    );
    echo $response->getTranslations()[0]->getTranslatedText();
    

First Use Case: Dynamic UI Localization

// In a Laravel controller or service
public function translateText(string $text, string $targetLang): string
{
    $client = app(TranslationServiceClient::class);
    $response = $client->translateText($text, [
        'targetLanguageCode' => $targetLang,
        'mimeType' => 'text/html', // For HTML content
    ]);
    return $response->getTranslations()[0]->getTranslatedText();
}

Implementation Patterns

1. Service Provider Integration

Register the client as a singleton in AppServiceProvider:

public function register()
{
    $this->app->singleton(TranslationServiceClient::class, function () {
        return new TranslationServiceClient();
    });
}

Usage:

$translation = app(TranslationServiceClient::class)->translateText(...);

2. Facade for Cleaner Code

Create a facade (app/Facades/Translate.php):

namespace App\Facades;

use Illuminate\Support\Facades\Facade;

class Translate extends Facade
{
    protected static function getFacadeAccessor() => 'google.translate';
}

Register in AppServiceProvider:

$this->app->bind('google.translate', function () {
    return new \Google\Cloud\Translate\V3\TranslationServiceClient();
});

Usage:

use App\Facades\Translate;

$translated = Translate::translateText('Hello', 'fr');

3. Queue-Based Batch Processing

For high-volume translations (e.g., bulk content updates), use Laravel queues:

// Job: TranslateTextJob.php
public function handle()
{
    $client = app(TranslationServiceClient::class);
    $response = $client->translateText($this->text, [
        'targetLanguageCode' => $this->targetLang,
    ]);
    $this->updateTranslatedContent($response->getTranslatedText());
}

Dispatch jobs in batches:

TranslateTextJob::dispatchEach($texts, 'es')->onQueue('translations');

4. Language Detection

Auto-detect source language:

$response = $client->detectLanguage('Bonjour le monde!');
$sourceLang = $response->getLanguages()[0]->getLanguageCode();

5. Adaptive Machine Translation (Advanced)

Fine-tune translations for domain-specific terminology:

$datasetName = 'projects/YOUR_PROJECT/locations/global/adaptiveMtDatasets/YOUR_DATASET';
$response = $client->translateText('Medical term', [
    'targetLanguageCode' => 'de',
    'adaptiveMtDatasetName' => $datasetName,
]);

6. Document Translation (PDF/DOCX)

Translate entire documents:

$gcsUri = 'gs://your-bucket/document.pdf';
$response = $client->translateDocument(
    $gcsUri,
    ['targetLanguageCode' => 'ja']
);

7. Glossary Integration

Customize translations with domain-specific terms:

$glossaryName = 'projects/YOUR_PROJECT/locations/global/glossaries/YOUR_GLOSSARY';
$response = $client->translateText('Term to translate', [
    'targetLanguageCode' => 'es',
    'glossaryConfig' => ['glossary' => $glossaryName],
]);

8. Error Handling

Wrap API calls in a service class:

public function safeTranslate(string $text, string $targetLang): ?string
{
    try {
        $response = $client->translateText($text, ['targetLanguageCode' => $targetLang]);
        return $response->getTranslations()[0]->getTranslatedText();
    } catch (\Google\ApiCore\ApiException $e) {
        \Log::error('Translation failed: ' . $e->getMessage());
        return null;
    }
}

Gotchas and Tips

Authentication Pitfalls

  1. Service Account Permissions:

    • Ensure the service account has the roles/cloudtranslate.user role.
    • Avoid using default credentials in production (always use explicit JSON keys).
  2. Environment Variables:

    • Laravel’s .env may not load GOOGLE_APPLICATION_CREDENTIALS automatically. Use:
      putenv('GOOGLE_APPLICATION_CREDENTIALS=' . env('GOOGLE_CREDENTIALS_PATH'));
      
  3. Deprecated credentials Option:

    • Avoid passing credentials directly to the client constructor (deprecated in v2.1.0). Use environment variables or putenv() instead.

Performance Tips

  1. Caching:

    • Cache translations for static content (e.g., marketing pages) using Laravel’s cache:
      $cacheKey = "translate:{$text}:{$targetLang}";
      return cache()->remember($cacheKey, now()->addHours(1), function () use ($text, $targetLang) {
          return $this->safeTranslate($text, $targetLang);
      });
      
  2. Batch Requests:

    • For multiple translations, use translateText in a loop or batch via DocumentTranslation.
  3. Async Processing:

    • Offload translations to a queue to avoid blocking HTTP requests:
      TranslateTextJob::dispatch($text, $targetLang)->onQueue('translations');
      return response()->json(['status' => 'queued']);
      

Common Errors & Fixes

Error Cause Solution
InvalidArgument: Invalid target language code Invalid ISO code (e.g., en-US instead of en) Use 2-letter codes (e.g., es, fr).
ApiException: Quota exceeded Hitting Google’s free tier limits (~500K characters/day) Upgrade quota or implement exponential backoff.
ApiException: Request contains an invalid argument Malformed request (e.g., missing mimeType) Validate inputs; check API docs.
ApiException: 403 Forbidden Missing permissions on the service account Grant roles/cloudtranslate.user to the account.

Debugging

  1. Enable Logging:

    • Add a logger to the client:
      $client = new TranslationServiceClient([
          'logger' => new \Monolog\Logger('translate', [
              new \Monolog\Handler\StreamHandler(storage_path('logs/translate.log'), \Monolog\Logger::DEBUG),
          ]),
      ]);
      
  2. Retry Logic:

    • Implement exponential backoff for transient errors:
      use Google\ApiCore\RetrySettings;
      
      $retrySettings = new RetrySettings();
      $retrySettings->setMaxAttempts(3);
      $client = new TranslationServiceClient(['retrySettings' => $retrySettings]);
      
  3. Validate Responses:

    • Always check getTranslations() length (may return empty for unsupported pairs):
      if (empty($response->getTranslations())) {
          throw new \RuntimeException('Translation failed for language pair.');
      }
      

Extension Points

  1. Custom Response Handling:

    • Extend the client to add metadata (e.g., confidence scores):
      $client->translateText($text, ['targetLanguageCode' => 'de'])->then(function ($response) {
          $translation = $response->getTranslations()[0];
          $data = [
              'text' => $translation->getTranslatedText(),
              'confidence' => $translation->getDetectedLanguageCode() === 'auto' ? 0.9 : 0.7,
          ];
          return $data;
      });
      
  2. Pre/Post-Processing:

    • Clean text before translation (e.g., remove HTML tags):
      $cleanText = strip_tags($dirtyText);
      $translated = $client->translateText($cleanText, ['targetLanguageCode' => 'es']);
      
  3. Fallback Logic:

    • Handle uns
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