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

Translator Laravel Package

yiisoft/translator

yiisoft/translator is a lightweight PHP translation library for managing messages, locales, and pluralization. Integrates with Yii and PSR-style components, supports multiple message sources and fallback locales, and is suitable for apps and libraries needing i18n.

Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require yiisoft/translator
    

    Register the service provider in config/app.php:

    'providers' => [
        // ...
        Yiisoft\Translator\Translator::class,
    ],
    
  2. Basic Configuration Define translations in a structured directory (e.g., resources/lang/):

    resources/
    └── lang/
        ├── en/
        │   └── messages.php
        └── es/
            └── messages.php
    

    Example messages.php (English):

    return [
        'welcome' => 'Welcome to our application!',
        'greeting' => 'Hello, :name!',
    ];
    
  3. First Translation Inject the Translator into a controller or service:

    use Yiisoft\Translator\Translator;
    
    public function __construct(private Translator $translator) {}
    
    public function greet(string $name): string
    {
        return $this->translator->translate('greeting', ['name' => $name]);
    }
    

    Call it in a route:

    Route::get('/greet/{name}', [YourController::class, 'greet']);
    
  4. Language Switching Set the locale dynamically (e.g., via middleware):

    $translator->setLocale('es'); // Switch to Spanish
    

Implementation Patterns

1. Translation Files Organization

  • Hierarchical Structure: Use nested arrays for modular translations (e.g., resources/lang/en/auth.php):

    return [
        'login' => [
            'title' => 'Sign In',
            'submit' => 'Login',
        ],
    ];
    

    Translate with:

    $this->translator->translate('auth.login.title');
    
  • Fallbacks: Define a fallback locale in config (e.g., en):

    $translator->setFallbackLocale('en');
    

2. Dynamic Content

  • Placeholders: Use named placeholders (e.g., :name, :count):

    $this->translator->translate('greeting', ['name' => 'John']);
    

    Translation file:

    'greeting' => 'Hello, :name! You have :count messages.',
    
  • Pluralization: Support plural rules (e.g., resources/lang/en/rules.php):

    return [
        'messages' => [
            '{0} No messages',
            '{1} One message',
            '[2,Inf] {0} messages',
        ],
    ];
    

    Usage:

    $this->translator->translate('messages', [], 5);
    

3. Integration with Laravel

  • Service Binding: Bind the translator to Laravel’s container in AppServiceProvider:

    public function register()
    {
        $this->app->singleton(Translator::class, function ($app) {
            return new Translator(
                new FileMessageSource('resources/lang'),
                $app['config']['app.locale']
            );
        });
    }
    
  • View Composers: Load translations for views:

    public function compose(View $view)
    {
        $view->with('translations', $this->translator->getCatalog());
    }
    
  • Form Requests: Validate with translated messages:

    public function messages()
    {
        return [
            'required' => trans('validation.required'),
        ];
    }
    

4. Caching Translations

  • Catalog Caching: Cache the loaded catalog for performance:
    $translator->setCatalogCache(new FileCache('runtime/cache/translations'));
    

5. Custom Message Sources

  • Database Backend: Extend MessageSource for dynamic translations:
    class DatabaseMessageSource implements MessageSource
    {
        public function getMessage(string $category, string $message, array $params = []): string
        {
            // Fetch from DB and return translated message
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Missing Fallback Locale

    • If the primary locale fails to load, the translator throws an exception. Always set a fallback:
      $translator->setFallbackLocale('en');
      
  2. Case Sensitivity in Keys

    • Translation keys are case-sensitive. Ensure consistency:
      // Fails if defined as 'welcome' but called as 'Welcome'
      $this->translator->translate('Welcome');
      
  3. Circular Dependencies in Plural Rules

    • Avoid recursive plural rules (e.g., referencing other plural rules). Test edge cases like {0} or {1}.
  4. File Permissions

    • If using file caching, ensure the runtime/cache directory is writable:
      chmod -R 775 runtime/cache
      

Debugging

  1. Check Loaded Catalog Dump the current catalog to verify translations are loaded:

    dd($this->translator->getCatalog());
    
  2. Validate Translation Files Use PHP’s var_dump to inspect loaded files:

    var_dump(require 'resources/lang/en/messages.php');
    
  3. Locale-Specific Issues

    • Test translations in all target locales early. Some languages (e.g., Arabic) require right-to-left (RTL) support in templates.

Tips

  1. Use Translation Keys in Code

    • Avoid hardcoding strings. Always use translator->translate() or the trans() helper (if integrated).
  2. Leverage Laravel’s trans() Helper If using Laravel, alias the translator for convenience:

    // In AppServiceProvider
    app()->bind('trans', function () {
        return app(Translator::class);
    });
    

    Usage:

    trans('messages.welcome');
    
  3. Environment-Specific Translations Override translations per environment (e.g., resources/lang/en/dev.php for development-specific messages).

  4. Validation Messages Extend Laravel’s validator with custom translated messages:

    Validator::extend('custom_rule', function ($attribute, $value, $parameters, $validator) {
        return $value > 0;
    });
    
    Validator::replacer('custom_rule', function ($message, $attribute, $rule, $parameters) {
        return trans('validation.custom_rule', ['attribute' => $attribute]);
    });
    
  5. Performance Optimization

    • Cache the catalog aggressively in production:
      $translator->setCatalogCache(new FileCache('runtime/cache/translations', 3600)); // 1-hour cache
      
    • Disable caching in development for live updates:
      $translator->setCatalogCache(null);
      
  6. Testing Translations

    • Write PHPUnit tests to verify translations:
      public function testTranslations()
      {
          $translator = new Translator(new FileMessageSource('tests/lang'), 'en');
          $this->assertEquals('Welcome!', $translator->translate('welcome'));
      }
      
  7. Extending with Custom Functions

    • Add helper methods to the translator for domain-specific logic:
      $translator->setCustomFunction('format_date', function ($date) {
          return trans('dates.format', ['date' => $date->format('F j, Y')]);
      });
      
      Usage:
      $this->translator->translate('custom.format_date', ['date' => now()]);
      
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