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. Set up authentication (follow Google Cloud PHP Auth Guide):
    • Use a service account JSON key (recommended for Laravel):
      putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/your-service-account.json');
      
    • Or configure via Laravel’s .env:
      GOOGLE_APPLICATION_CREDENTIALS=/path/to/your-service-account.json
      
  3. First translation call (V3 client, preferred for new projects):
    use Google\Cloud\Translate\V3\TranslationServiceClient;
    
    $client = new TranslationServiceClient();
    $response = $client->translateText(
        (new \Google\Cloud\Translate\V3\TranslateTextRequest())
            ->setContents(['Hello, world!'])
            ->setMimeType('text/plain')
            ->setTargetLanguageCode('es')
    );
    echo $response->getTranslations()[0]->getTranslatedText();
    

Key First Use Cases

  • Dynamic UI localization: Translate error messages, buttons, or user inputs in real-time.
  • Content management: Automate translation of blog posts, product descriptions (via Eloquent observers or jobs).
  • API responses: Wrap API responses in a middleware to translate based on Accept-Language headers.

Implementation Patterns

Core Workflows

1. Service Container Integration (Laravel-Specific)

Bind the client to Laravel’s container in AppServiceProvider:

use Illuminate\Support\ServiceProvider;
use Google\Cloud\Translate\V3\TranslationServiceClient;

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

Usage in controllers:

use Google\Cloud\Translate\V3\TranslationServiceClient;

class TranslationController extends Controller
{
    public function __construct(private TranslationServiceClient $client) {}

    public function translate(string $text, string $targetLang)
    {
        $response = $this->client->translateText(
            (new \Google\Cloud\Translate\V3\TranslateTextRequest())
                ->setContents([$text])
                ->setTargetLanguageCode($targetLang)
        );
        return $response->getTranslations()[0]->getTranslatedText();
    }
}

2. Middleware for Automatic Language Detection

Create middleware to translate responses based on Accept-Language:

use Closure;
use Google\Cloud\Translate\V3\TranslationServiceClient;

class TranslateResponseMiddleware
{
    public function __construct(private TranslationServiceClient $client) {}

    public function handle($request, Closure $next)
    {
        $response = $next($request);
        $targetLang = $request->header('Accept-Language') ?? 'en';

        if ($targetLang !== 'en' && $response->getContent()) {
            $translated = $this->client->translateText(
                (new \Google\Cloud\Translate\V3\TranslateTextRequest())
                    ->setContents([$response->getContent()])
                    ->setTargetLanguageCode($targetLang)
            );
            $response->setContent($translated->getTranslations()[0]->getTranslatedText());
        }

        return $response;
    }
}

Register in app/Http/Kernel.php:

protected $middleware = [
    // ...
    \App\Http\Middleware\TranslateResponseMiddleware::class,
];

3. Eloquent Model Observers for Automatic Translation

Translate model attributes on save (e.g., for a Post model):

use Google\Cloud\Translate\V3\TranslationServiceClient;
use Illuminate\Database\Eloquent\Model;

class PostObserver
{
    public function __construct(private TranslationServiceClient $client) {}

    public function saving(Model $post)
    {
        if ($post->isDirty('title') && $post->target_language) {
            $translated = $this->client->translateText(
                (new \Google\Cloud\Translate\V3\TranslateTextRequest())
                    ->setContents([$post->title])
                    ->setTargetLanguageCode($post->target_language)
            );
            $post->translated_title = $translated->getTranslations()[0]->getTranslatedText();
        }
    }
}

Register in Post model:

protected static function booted()
{
    static::observe(new PostObserver(app(TranslationServiceClient::class)));
}

4. Batch Processing with Queues

Offload translations to a queue for high-volume tasks (e.g., translating 10K product descriptions):

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Google\Cloud\Translate\V3\TranslationServiceClient;

class TranslateProductsJob implements ShouldQueue
{
    use Queueable;

    public function __construct(
        private array $productTitles,
        private string $targetLang
    ) {}

    public function handle(TranslationServiceClient $client)
    {
        $request = (new \Google\Cloud\Translate\V3\TranslateTextRequest())
            ->setContents($this->productTitles)
            ->setTargetLanguageCode($this->targetLang);

        $response = $client->translateText($request);
        // Save translations to database...
    }
}

Dispatch from a command or controller:

TranslateProductsJob::dispatch($productTitles, 'fr')->onQueue('translations');

5. Caching Translations

Cache frequent translations (e.g., UI labels) to reduce API calls:

use Illuminate\Support\Facades\Cache;

public function translateCached(string $text, string $targetLang, string $cacheKey)
{
    return Cache::remember($cacheKey, now()->addHours(1), function () use ($text, $targetLang) {
        return $this->client->translateText(
            (new \Google\Cloud\Translate\V3\TranslateTextRequest())
                ->setContents([$text])
                ->setTargetLanguageCode($targetLang)
        )->getTranslations()[0]->getTranslatedText();
    });
}

Advanced Patterns

Adaptive Machine Translation (Domain-Specific Models)

For high-accuracy translations (e.g., legal/medical text):

use Google\Cloud\Translate\V3\AdaptiveMtDataset;
use Google\Cloud\Translate\V3\TranslationServiceClient;

public function translateWithAdaptiveModel(string $text, string $modelId)
{
    $request = (new \Google\Cloud\Translate\V3\TranslateTextRequest())
        ->setContents([$text])
        ->setMimeType('text/plain')
        ->setModel($modelId); // e.g., 'projects/YOUR_PROJECT/locations/us/collections/default_models/models/YOUR_MODEL'

    return $this->client->translateText($request);
}

Glossary-Based Translation

Maintain consistent terminology (e.g., brand names):

use Google\Cloud\Translate\V3\Glossary;
use Google\Cloud\Translate\V3\TranslationServiceClient;

public function translateWithGlossary(string $text, string $glossaryName)
{
    $request = (new \Google\Cloud\Translate\V3\TranslateTextRequest())
        ->setContents([$text])
        ->setGlossaryConfig([
            'glossary' => $glossaryName,
            'project' => 'projects/YOUR_PROJECT',
            'location' => 'us',
        ]);

    return $this->client->translateText($request);
}

Document Translation (PDFs, HTML)

Translate entire documents (e.g., user uploads):

use Google\Cloud\Translate\V3\TranslationServiceClient;

public function translateDocument(string $filePath, string $targetLang)
{
    $response = $this->client->translateDocument(
        (new \Google\Cloud\Translate\V3\TranslateDocumentRequest())
            ->setGcsSource(['inputUri' => "gs://your-bucket/$filePath"])
            ->setMimeType('application/pdf')
            ->setTargetLanguageCode($targetLang)
    );
    // Process $response->getOutputConfig()->getGcsDestination()->getOutputUri()
}

Gotchas and Tips

Pitfalls and Debugging

1. Authentication Issues

  • Symptom: Google\Auth\Exception\GoogleAuthException: Could not load credentials.
  • Fix:
    • Ensure GOOGLE_APPLICATION_CREDENTIALS is set in .env or via putenv().
    • Verify the service account has the Cloud Translation API User role.
    • For Laravel Forge/Laravel Vapor, upload the JSON key to the server and reference its path in .env.

2. Quota Exceeded Errors

  • Symptom: 429 Too Many Requests or RESOURCE_EXHAUSTED.
  • Fix:
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