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

Filament Translations Google Laravel Package

tomatophp/filament-translations-google

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require tomatophp/filament-translations-google
    

    Publish the config file:

    php artisan vendor:publish --provider="Tomato\FilamentTranslationsGoogle\FilamentTranslationsGoogleServiceProvider" --tag="config"
    
  2. Register the Package Add the service provider to config/app.php under providers:

    Tomato\FilamentTranslationsGoogle\FilamentTranslationsGoogleServiceProvider::class,
    
  3. Configure Google API Key Add your Google Cloud Translation API key to .env:

    GOOGLE_TRANSLATE_API_KEY=your_api_key_here
    

    Configure the supported languages in config/filament-translations-google.php:

    'supported_languages' => [
        'en' => 'English',
        'fr' => 'French',
        'es' => 'Spanish',
        // Add more as needed
    ],
    
  4. First Use Case: Auto-Translate Existing Strings Navigate to Filament Admin Panel > Translations Manager > Select a language (e.g., fr) > Click "Auto-Translate" to fetch and translate all __()/trans() strings from your source language (default: en).


Implementation Patterns

Workflow: Translating a New Language

  1. Add Language Support Extend config/filament-translations-google.php with new languages:

    'supported_languages' => [
        'en' => 'English',
        'de' => 'German', // New addition
    ],
    
  2. Trigger Auto-Translation

    • Use the Filament UI to auto-translate via the "Auto-Translate" button.
    • Or trigger programmatically:
      use Tomato\FilamentTranslationsGoogle\Facades\FilamentTranslationsGoogle;
      
      FilamentTranslationsGoogle::translate('de'); // Translate to German
      
  3. Manual Overrides After auto-translation, manually refine translations in the Filament Translations Manager for accuracy.


Integration with Laravel Localization

  • Dynamic Language Switching Use middleware to set the locale dynamically (e.g., based on user preference):

    public function handle($request, Closure $next)
    {
        $locale = $request->header('Accept-Language') ?? config('app.locale');
        app()->setLocale($locale);
        return $next($request);
    }
    
  • Fallback Logic Configure fallback locales in config/app.php:

    'fallback_locale' => 'en',
    
  • Blade Directives Use @translate in Blade templates for consistency:

    <h1>@translate('welcome.title')</h1>
    

Extending Functionality

  1. Custom Translation Sources Override the default __()/trans() parsing logic by extending the TranslationSource class:

    namespace App\Providers;
    
    use Tomato\FilamentTranslationsGoogle\TranslationSource;
    use Illuminate\Support\Facades\File;
    
    class CustomTranslationSource extends TranslationSource
    {
        public function getStrings(): array
        {
            $customStrings = File::get('custom-translations.json');
            return json_decode($customStrings, true);
        }
    }
    

    Bind it in a service provider:

    $this->app->bind(
        Tomato\FilamentTranslationsGoogle\TranslationSource::class,
        App\Providers\CustomTranslationSource::class
    );
    
  2. Batch Processing Schedule translations for multiple languages using Laravel Queues:

    use Tomato\FilamentTranslationsGoogle\Facades\FilamentTranslationsGoogle;
    use Illuminate\Support\Facades\Queue;
    
    Queue::push(function () {
        FilamentTranslationsGoogle::translate(['fr', 'es', 'de']);
    });
    

Gotchas and Tips

Pitfalls

  1. API Key Restrictions

    • Google Cloud Translation API has quota limits (free tier: 500,000 characters/month).
    • Monitor usage via Google Cloud Console.
    • Solution: Cache translations locally to avoid repeated API calls:
      'cache_translations' => true, // Enable in config
      
  2. Character Limits

    • Google API truncates strings longer than 10,000 characters per request.
    • Solution: Split long strings manually or pre-process them:
      use Tomato\FilamentTranslationsGoogle\Helpers\StringSplitter;
      
      $chunks = StringSplitter::split($longString, 5000);
      
  3. Rate Limiting

    • Exceeding rate limits (e.g., >100 requests/minute) may return 429 Too Many Requests.
    • Solution: Implement exponential backoff in your translation logic:
      try {
          FilamentTranslationsGoogle::translate($lang);
      } catch (\GuzzleHttp\Exception\RequestException $e) {
          if ($e->getCode() === 429) {
              sleep(30); // Wait 30 seconds
              retry();
          }
      }
      

Debugging

  1. Log Translation Failures Enable debug logging in config/filament-translations-google.php:

    'debug' => env('APP_DEBUG', false),
    

    Check logs at storage/logs/laravel.log for API errors.

  2. Verify API Key Test your API key manually:

    curl -X POST -H "Authorization: Bearer $GOOGLE_TRANSLATE_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{"q":"Hello","target":"fr"}' \
    "https://translation.googleapis.com/language/translate/v2"
    
  3. Clear Cache After Updates If translations appear stale:

    php artisan cache:clear
    php artisan view:clear
    

Tips

  1. Prioritize High-Impact Strings Use the "Translate Priority" feature in Filament to mark critical strings (e.g., error messages) for manual review after auto-translation.

  2. Localization Testing Simulate locale-specific content with Laravel’s app()->setLocale():

    app()->setLocale('fr');
    dd(__('welcome.title')); // Test French translation
    
  3. Cost Optimization

    • Exclude Unused Strings: Filter out strings not used in production by analyzing Blade templates or logs.
    • Batch Requests: Group translations into fewer API calls where possible.
  4. Fallback to Human Translation For low-quality auto-translations, integrate a manual review step:

    FilamentTranslationsGoogle::translate('de', [
        'require_review' => true, // Flag for manual check
    ]);
    
  5. Environment-Specific Config Override settings per environment (e.g., disable auto-translation in staging):

    'auto_translate_on_save' => env('APP_ENV') !== 'staging',
    
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope