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

Translation Laravel Package

symfony/translation

Symfony Translation component for internationalizing apps: manage translators, message catalogs, pluralization and locales, load translations from arrays/files, and translate strings with parameters and domains. Install via Composer and integrate in Symfony or standalone PHP.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

  1. Install the package via Composer:
    composer require symfony/translation
    
  2. Register the service provider in config/app.php (Laravel 8+ auto-discovers it):
    'providers' => [
        // ...
        Symfony\Component\Translation\TranslationServiceProvider::class,
    ],
    
  3. Publish the config (optional, but recommended for customization):
    php artisan vendor:publish --provider="Symfony\Component\Translation\TranslationServiceProvider" --tag="config"
    
  4. Configure locales in config/translation.php:
    'locales' => ['en', 'fr', 'es'],
    'default_locale' => 'en',
    'fallback_locale' => 'en',
    
  5. First translation usage in a Blade view or controller:
    // In a controller
    $translator = app('translator');
    echo $translator->trans('welcome.message', ['%name%' => 'John']);
    
    // In a Blade view
    @lang('welcome.message', ['name' => 'John'])
    

First Use Case: Localizing a Simple Message

  1. Create a translation file at resources/lang/fr/welcome.php:
    return [
        'message' => 'Bonjour :name, bienvenue !',
    ];
    
  2. Use it in your app:
    $translator->trans('welcome.message', ['name' => 'John']); // Outputs: "Bonjour John, bienvenue !"
    

Implementation Patterns

1. Loader Strategies for Different Use Cases

Scenario Loader Class Example Setup
Static translations ArrayLoader $translator->addResource('array', $translations, 'fr');
File-based (JSON/YAML/CSV) YamlFileLoader, JsonFileLoader $translator->addResource('yaml', 'path/to/translations.fr.yaml', 'fr');
Database-backed Custom loader (extend LoaderInterface) Use DoctrineDBALLoader or build a custom one for Eloquent.
XLIFF (Crowdin/Lokalise) XliffFileLoader $translator->addResource('xliff', 'translations.xlf', 'fr');
Dynamic (API responses) ArrayLoader + runtime data Load translations from an API and cache them.

Example: Dynamic Loader for API Translations

use Symfony\Component\Translation\Loader\LoaderInterface;

class ApiTranslationLoader implements LoaderInterface
{
    public function load($resource, $locale, $domain = 'messages')
    {
        $response = Http::get("https://api.example.com/translations/{$locale}");
        return json_decode($response, true);
    }
}

2. Message Domains for Organized Translations

Group translations by context (e.g., validation, notifications):

// In config/translation.php
'default_domain' => 'messages',
'domains' => [
    'validation' => 'resources/lang/*/validation.php',
    'notifications' => 'resources/lang/*/notifications.php',
],

// Usage
$translator->trans('validation.required', [], 'validation');

3. Pluralization and Interpolation

Handle plural forms and dynamic content:

// resources/lang/fr/messages.php
'items' => 'Vous avez |{0} aucun article|{1} un article|]1,Inf] {0} articles| articles.',
'greeting' => 'Bonjour, :name!',

// Usage
$translator->trans('items', ['%0%' => 5]); // "Vous avez 5 articles."
$translator->trans('greeting', ['name' => 'John']); // "Bonjour, John!"

4. Integration with Laravel’s Blade and Forms

  • Blade directives:
    @lang('messages.welcome')
    @choice('messages.items', $count)
    
  • Form validation messages:
    use Illuminate\Support\Facades\Validator;
    
    $validator = Validator::make($data, [
        'email' => 'required|email',
    ], [
        'email.required' => trans('validation.email_required'),
    ]);
    

5. Caching for Performance

Leverage Laravel’s cache to avoid reloading translations:

$translator = app('translator');
$translator->getCatalogue('fr')->setCache($cache); // Use Laravel's cache driver

6. Middleware for Locale Switching

// app/Http/Middleware/LocaleMiddleware.php
public function handle($request, Closure $next)
{
    $locale = $request->segment(1) ?? config('app.locale');
    app()->setLocale($locale);
    return $next($request);
}

7. Testing Translations

Use Laravel’s testing helpers:

public function test_translations()
{
    $this->assertEquals(
        'Bonjour John!',
        trans('welcome.greeting', ['name' => 'John'])
    );
}

Gotchas and Tips

Pitfalls

  1. Locale Fallback Chain:

    • If fr_CA is requested but only fr exists, ensure fallback_locale is set in config/translation.php to avoid errors.
    • Fix: Configure fallbacks explicitly:
      'fallbacks' => [
          'fr_CA' => ['fr', 'en'],
          'es_MX' => ['es', 'en'],
      ],
      
  2. Translation File Caching:

    • Laravel caches translation files aggressively. Clear the cache after adding new translations:
      php artisan config:clear
      php artisan view:clear
      
  3. XLIFF File Paths:

    • XLIFF files require URL-encoded paths in some environments (e.g., Docker). Use:
      $translator->addResource('xliff', urlencode('path/to/translations.xlf'), 'fr');
      
  4. Pluralization Rules:

    • Not all languages follow English pluralization rules. Use ICU syntax for accuracy:
      // resources/lang/fr/messages.php
      'apples' => 'Il y a |{0} zéro pomme|{1} une pomme|]1,Inf] {0} pommes|.',
      
  5. Namespace Collisions:

    • Avoid naming conflicts between domains (e.g., messages and messages.notifications). Use unique domains:
      $translator->trans('notifications.welcome', [], 'notifications');
      
  6. CSV Loader Quirks:

    • Empty lines in CSV files can break loading. Trim whitespace or use a custom loader:
      $translator->addResource('csv', 'translations.csv', 'fr', 'messages');
      

Debugging Tips

  1. Check Loaded Resources:

    $catalogue = $translator->getCatalogue('fr');
    dump($catalogue->getResources());
    
  2. Enable Debug Mode:

    $translator->setFallbackLocale('en');
    $translator->setDebug(true); // Logs missing translations
    
  3. Validate Translation Files: Use Laravel’s lang:publish to regenerate files:

    php artisan lang:publish
    

Extension Points

  1. Custom Loaders: Extend LoaderInterface for database/API-based translations:

    class EloquentLoader implements LoaderInterface
    {
        public function load($resource, $locale, $domain = 'messages')
        {
            return Translation::where('locale', $locale)
                ->where('domain', $domain)
                ->pluck('message', 'id')
                ->toArray();
        }
    }
    
  2. Message Extractors: Automate translation key extraction with a custom MessageExtractorInterface:

    class LaravelMessageExtractor implements MessageExtractorInterface
    {
        public function extract($file, $locale, $domain)
        {
            // Parse Blade files for `@lang()` directives
        }
    }
    
  3. Translation Dumpers: Export translations to external services (e.g., Crowdin):

    use Symfony\Component\Translation\Dumper\XliffFileDumper;
    
    $dumper = new XliffFileDumper();
    $dumper->dump($catalogue, 'translations.xlf');
    
  4. Middleware for Locale Detection: Dynamically set locale based on:

    • User preference (database)
    • Accept-Language header
    • Subdomain (e.g., fr.app.com)

Performance Optimizations

  1. Preload Translations:
    $translator->getCatalog
    
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.
codraw/entity-migrator
codraw/doctrine-extra
codraw/aws-tool-kit
codraw/validator
codraw/workflow
codraw/open-api
codraw/cron-job
codraw/process
codraw/log
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony