darvis/laravel-google-translate
Composer 安装命令:
composer require darvis/laravel-google-translate
包简介
Google Translate integration for Laravel with support for translatable models
关键字:
README 文档
README
Google Translate integration for Laravel with support for translatable Eloquent models.
Features
- 🌍 Simple Translation API - Translate text and HTML content
- 📦 Model Trait - Easy integration with Eloquent models
- 🔄 Batch Translation - Translate multiple texts at once
- 📝 HTML Support - Preserve HTML tags during translation
- ⚙️ Configurable - Customize source and target locales
Requirements
- PHP 8.2+
- Laravel 11.x, 12.x, or 13.x
- Google Cloud Translation API key
Installation
Install the package via Composer:
composer require darvis/laravel-google-translate
Publish the configuration file:
php artisan vendor:publish --tag=google-translate-config
Add your Google Translate API key to your .env file:
GOOGLE_TRANSLATE_API_KEY=your-api-key-here GOOGLE_TRANSLATE_SOURCE_LOCALE=nl GOOGLE_TRANSLATE_TARGET_LOCALES=en,de,fr
Usage
Basic Translation
use Darvis\LaravelGoogleTranslate\GoogleTranslateService; $translator = app(GoogleTranslateService::class); // Translate text $translated = $translator->translate('Hallo wereld', 'en'); // Result: "Hello world" // Translate HTML (preserves tags) $translated = $translator->translateHtml('<p>Hallo <strong>wereld</strong></p>', 'en'); // Result: "<p>Hello <strong>world</strong></p>" // Batch translate $translations = $translator->translateBatch(['Hallo', 'Wereld'], 'en'); // Result: ['Hello', 'World']
Model Integration
Add the HasGoogleTranslate trait to your Eloquent model:
use Darvis\LaravelGoogleTranslate\Traits\HasGoogleTranslate; use Illuminate\Database\Eloquent\Model; class Page extends Model { use HasGoogleTranslate; protected $fillable = [ 'pid', 'locale', 'title', 'content', 'description', // ... ]; // Define which fields should be translated protected array $translatableFields = [ 'title', 'content', 'description', 'seo_title', 'seo_description', ]; // Define which fields contain HTML protected array $htmlFields = [ 'content', 'description', ]; }
Creating Translations
$page = Page::find(1); // Dutch page // Create English translation $englishPage = $page->createTranslation('en', [ 'slug' => $page->slug, 'active' => true, ]); // Check if translation exists if ($page->hasTranslation('en')) { $translation = $page->getTranslation('en'); } // Get all translations $allTranslations = $page->getAllTranslations();
Filling Missing Translations
$englishPage = Page::where('locale', 'en')->first(); // Fill empty fields from Dutch source $result = $englishPage->fillMissingTranslations('nl'); // $result = [ // 'translated' => ['title', 'content'], // 'errors' => [], // ]
Finding Missing Translations
// Get all Dutch pages without English translation $missing = Page::getMissingTranslations('en', 'nl'); foreach ($missing as $page) { $page->createTranslation('en'); }
Scopes
// Get only source items (no pid) $sourcePages = Page::sourceItems()->get(); // Get items in current locale $localizedPages = Page::localized()->get(); // Get items in specific locale $dutchPages = Page::localized('nl')->get();
Configuration
// config/google-translate.php return [ // Your Google Cloud Translation API key 'api_key' => env('GOOGLE_TRANSLATE_API_KEY'), // Default source locale 'source_locale' => env('GOOGLE_TRANSLATE_SOURCE_LOCALE', 'nl'), // Target locales (comma-separated in .env) 'target_locales' => explode(',', env('GOOGLE_TRANSLATE_TARGET_LOCALES', 'en')), ];
Database Structure
Your translatable models should have:
localecolumn (string) - The language code (e.g., 'nl', 'en')pidcolumn (nullable integer) - Parent ID pointing to the source item
Example migration:
Schema::create('pages', function (Blueprint $table) { $table->id(); $table->foreignId('pid')->nullable()->constrained('pages')->nullOnDelete(); $table->string('locale', 5)->default('nl'); $table->string('title'); $table->text('content')->nullable(); // ... $table->timestamps(); $table->index(['locale', 'pid']); });
API Reference
GoogleTranslateService
| Method | Description |
|---|---|
isAvailable() |
Check if API key is configured |
translate($text, $targetLocale, $sourceLocale) |
Translate plain text |
translateHtml($html, $targetLocale, $sourceLocale) |
Translate HTML content |
translateBatch($texts, $targetLocale, $sourceLocale) |
Translate multiple texts |
translateFields($fields, $targetLocale, $sourceLocale, $htmlFields) |
Translate array of fields |
getSourceLocale() |
Get configured source locale |
getTargetLocales() |
Get configured target locales |
HasGoogleTranslate Trait
| Method | Description |
|---|---|
hasTranslation($locale) |
Check if translation exists |
getTranslation($locale) |
Get translation for locale |
getAllTranslations() |
Get all translations including self |
createTranslation($locale, $attributes) |
Create new translation |
fillMissingTranslations($sourceLocale) |
Fill empty fields from source |
getTranslatableFields() |
Get list of translatable fields |
getHtmlFields() |
Get list of HTML fields |
Scopes
| Scope | Description |
|---|---|
sourceItems() |
Only items without pid (originals) |
localized($locale) |
Items in specific locale |
Static Methods
| Method | Description |
|---|---|
getMissingTranslations($targetLocale, $sourceLocale) |
Get items missing translation |
CMS Integration
For a complete guide on building a Translation Check Dashboard for your CMS, see the CMS Integration Guide.
Key features:
- Overview of missing translations per module
- Bulk translation with one click
- Individual item translation
- API status monitoring
- Progress tracking per locale
Testing
composer test
License
The MIT License (MIT). Please see License File for more information.
Author
- Arvid de Jong - info@arvid.nl
darvis/laravel-google-translate 适用场景与选型建议
darvis/laravel-google-translate 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 7 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 01 月 26 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「i18n」 「translation」 「laravel」 「localization」 「eloquent」 「multilingual」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 darvis/laravel-google-translate 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 darvis/laravel-google-translate 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 darvis/laravel-google-translate 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Easy to use i18n translation PHP class for multi-language websites
A custom URL rule class for Yii 2 which allows to create translated URL rules
A Laravel Eloquent model trait for translatable resource
Bureaux A Partager Edit - Parse, validate, manipulate, and display dates in PHP w/ i18n support. Inspired by moment.js
Nette Framework adapter for I18n package
Yii2 integration for AirBnB Polyglot.js
统计信息
- 总下载量: 7
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 28
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2026-01-26