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
putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/your-service-account.json');
.env:
GOOGLE_APPLICATION_CREDENTIALS=/path/to/your-service-account.json
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();
Accept-Language headers.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();
}
}
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,
];
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)));
}
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');
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();
});
}
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);
}
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);
}
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()
}
Google\Auth\Exception\GoogleAuthException: Could not load credentials.GOOGLE_APPLICATION_CREDENTIALS is set in .env or via putenv()..env.429 Too Many Requests or RESOURCE_EXHAUSTED.How can I help you explore Laravel packages today?