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.
composer require google/cloud-translate
GOOGLE_APPLICATION_CREDENTIALS environment variable pointing to your service account JSON key..env:
GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json
use Google\Cloud\Translate\V3\TranslationServiceClient;
$client = new TranslationServiceClient();
$response = $client->translate('Hello world', ['targetLanguageCode' => 'es']);
echo $response->getTranslations()[0]->getTranslatedText(); // "Hola mundo"
// In a Laravel controller
public function translateUserPost(Request $request)
{
$client = new TranslationServiceClient();
$text = $request->input('content');
$targetLang = $request->input('target_lang', 'en');
$response = $client->translate($text, [
'targetLanguageCode' => $targetLang,
'mimeType' => 'text/plain' // Optional: for HTML/rich text, use 'text/html'
]);
return response()->json([
'translated' => $response->getTranslations()[0]->getTranslatedText(),
'detectedSource' => $response->getDetectedSourceLanguage()
]);
}
TranslationServiceClient) supports gRPC (faster) and newer features like AdaptiveMT.Cache::remember) to avoid repeated API calls for identical text.try-catch for Google\ApiCore\ApiException (e.g., quota limits, invalid input).Create a dedicated service class to abstract API calls:
// app/Services/TranslationService.php
namespace App\Services;
use Google\Cloud\Translate\V3\TranslationServiceClient;
use Google\ApiCore\ApiException;
class TranslationService
{
protected TranslationServiceClient $client;
public function __construct()
{
$this->client = new TranslationServiceClient();
}
public function translate(string $text, string $targetLang = 'en'): string
{
try {
$response = $this->client->translate($text, [
'targetLanguageCode' => $targetLang,
'model' => 'base' // or 'adaptive' for AdaptiveMT
]);
return $response->getTranslations()[0]->getTranslatedText();
} catch (ApiException $e) {
\Log::error("Translation failed: {$e->getMessage()}");
throw new \RuntimeException("Translation service unavailable.");
}
}
}
Usage in Controller:
public function __invoke(Request $request)
{
$translation = app(TranslationService::class)->translate(
$request->text,
$request->target_lang
);
// ...
}
For long-running translations (e.g., batch processing), use Laravel Queues:
// app/Jobs/TranslateTextJob.php
namespace App\Jobs;
use App\Services\TranslationService;
use Illuminate\Bus\Queueable;
class TranslateTextJob
{
use Queueable;
public function handle(TranslationService $service)
{
$text = 'Your text to translate';
$translation = $service->translate($text, 'fr');
// Store result in DB or send notification
}
}
Dispatch:
TranslateTextJob::dispatch()->onQueue('translations');
For multiple texts (e.g., CSV imports):
public function batchTranslate(array $texts, string $targetLang): array
{
$requests = [];
foreach ($texts as $text) {
$requests[] = (new TranslateTextRequest())
->setContents($text)
->setMimeType('text/plain');
}
$response = $this->client->batchTranslate([
'parent' => 'projects/YOUR_PROJECT_ID/locations/global',
'requests' => $requests,
'targetLanguageCode' => $targetLang
]);
return array_map(
fn($t) => $t->getTranslatedText(),
$response->getTranslations()
);
}
For domain-specific translations (e.g., legal, medical):
// Train a custom model first (via Google Cloud Console)
// Then use it:
$response = $client->translate($text, [
'targetLanguageCode' => 'de',
'model' => 'projects/YOUR_PROJECT_ID/locations/us/glossaries/YOUR_GLOSSARY_ID'
]);
$response = $client->detectLanguage('Bonjour le monde');
echo $response->getLanguageCodes()[0]; // "fr"
use Google\Cloud\Translate\V3\TranslateDocumentRequest;
$gcsUri = 'gs://your-bucket/document.pdf';
$response = $client->translateDocument((new TranslateDocumentRequest())
->setParent('projects/YOUR_PROJECT_ID/locations/global')
->setGcsSource(['inputUri' => $gcsUri])
->setMimeType('application/pdf')
->setTargetLanguageCode('en')
);
foreach ($response->getTranslations() as $translation) {
echo $translation->getTranslatedText();
}
Extend Laravel’s AppServiceProvider:
public function boot()
{
view()->composer('*', function ($view) {
$view->with('translations', collect([
'greeting' => app(TranslationService::class)->translate(
'Hello',
app()->getLocale()
),
]));
});
}
Use mocks for unit tests (e.g., with Mockery):
public function test_translation_service()
{
$mockClient = Mockery::mock(TranslationServiceClient::class);
$mockClient->shouldReceive('translate')
->once()
->andReturn((new TranslateTextResponse())
->setTranslations([(new TranslatedText())
->setTranslatedText('Hola')])
);
$service = new TranslationService($mockClient);
$this->assertEquals('Hola', $service->translate('Hello', 'es'));
}
Service Account Permissions:
roles/cloudtranslate.user) role.PERMISSION_DENIED errors without clear logs. Use:
gcloud projects add-iam-policy-binding YOUR_PROJECT_ID \
--member="serviceAccount:YOUR_SERVICE_ACCOUNT@YOUR_PROJECT_ID.iam.gserviceaccount.com" \
--role="roles/cloudtranslate.user"
Environment Variables:
.env must load the JSON key before the client initializes. Use:
putenv('GOOGLE_APPLICATION_CREDENTIALS=' . storage_path('app/google-credentials.json'));
Local Development:
gcloud auth application-default login
Free Tier:
Quota Limits:
RESOURCE_EXHAUSTED.use Google\ApiCore\RetrySettings;
$retrySettings = new RetrySettings();
$retrySettings->setMaxAttempts(3);
$retrySettings->setInitialRetryDelay(0.1);
$retrySettings->setRetryDelayMultiplier(2);
$retrySettings->setMaxRetryDelay(10);
$client = new TranslationServiceClient(['retrySettings' => $retrySettings]);
Pricing:
How can I help you explore Laravel packages today?