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

php-translation/translator

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require php-translation/translator
    

    Register the service provider in config/app.php:

    'providers' => [
        PHPTranslation\Translator\TranslatorServiceProvider::class,
    ],
    
  2. Configuration Publish the config file:

    php artisan vendor:publish --provider="PHPTranslation\Translator\TranslatorServiceProvider" --tag="config"
    

    Update config/translator.php with your locales and paths:

    'locales' => ['en', 'es', 'fr'],
    'paths' => [base_path('resources/lang')],
    
  3. First Use Case Create a translation file (e.g., resources/lang/en/messages.php):

    return [
        'welcome' => 'Welcome, :name!',
        'errors' => [
            'not_found' => 'The resource you requested could not be found.',
        ],
    ];
    

    Use in a controller:

    use PHPTranslation\Translator\Translator;
    
    public function showWelcome(Translator $translator)
    {
        return $translator->trans('messages.welcome', ['name' => 'John']);
    }
    
  4. Language Switching Set the locale dynamically:

    app('translator')->setLocale('es');
    

    Or use middleware to detect language from Accept-Language header or URL:

    public function handle($request, Closure $next)
    {
        $locale = $request->header('Accept-Language') ?: 'en';
        app('translator')->setLocale($locale);
        return $next($request);
    }
    

Implementation Patterns

Core Usage Patterns

  1. Basic Translation

    $translator->trans('messages.welcome', ['name' => 'John']);
    // Output: "Welcome, John!"
    
  2. Pluralization

    $translator->transChoice('messages.items', $count, ['count' => $count]);
    // Example in `messages.php`:
    // return ['items' => '{count} item|{count} items'];
    
  3. Fallback Logic Configure fallbacks in config/translator.php:

    'fallbacks' => [
        'es' => ['ca'],
        'fr' => ['en'],
    ],
    

    If es.messages.welcome is missing, it falls back to ca.messages.welcome, then en.messages.welcome.

  4. Custom Loaders Register a custom loader in config/translator.php:

    'loaders' => [
        'json' => PHPTranslation\Translator\Loader\JsonLoader::class,
        'database' => App\Loaders\DatabaseLoader::class,
    ],
    

    Implement LoaderInterface for database/API sources:

    class DatabaseLoader implements LoaderInterface {
        public function load($locale, $group, $file) {
            return DB::table('translations')
                ->where('locale', $locale)
                ->where('group', $group)
                ->where('key', $file)
                ->pluck('value', 'key')
                ->toArray();
        }
    }
    
  5. Interpolation Use placeholders in translations:

    // In messages.php
    'greeting' => 'Hello, :name! Today is :date.',
    // In code
    $translator->trans('messages.greeting', [
        'name' => 'John',
        'date' => now()->format('Y-m-d'),
    ]);
    

Laravel-Specific Patterns

  1. Facade Usage Create a facade for cleaner syntax:

    // app/Facades/Translator.php
    namespace App\Facades;
    use Illuminate\Support\Facades\Facade;
    class Translator extends Facade {
        protected static function getFacadeAccessor() {
            return 'translator';
        }
    }
    

    Use in Blade or controllers:

    Translator::trans('messages.welcome');
    
  2. Middleware for Language Detection

    namespace App\Http\Middleware;
    use Closure;
    class SetLocale {
        public function handle($request, Closure $next) {
            $locale = $request->segment(1) ?: config('app.locale');
            app('translator')->setLocale($locale);
            return $next($request);
        }
    }
    

    Register in app/Http/Kernel.php:

    protected $middlewareGroups = [
        'web' => [
            // ...
            \App\Http\Middleware\SetLocale::class,
        ],
    ];
    
  3. View Localization Use @lang in Blade:

    @lang('messages.welcome', ['name' => $user->name])
    

    Or create a custom directive:

    Blade::directive('t', function ($expression) {
        return "<?php echo trans($expression); ?>";
    });
    

    Usage:

    @t("messages.welcome")
    
  4. Validation Messages Localize validation errors:

    $validator = Validator::make($request->all(), [
        'email' => 'required|email',
    ]);
    $validator->setCustomMessages([
        'email.required' => trans('validation.email.required'),
    ]);
    
  5. Caching Translations Use Laravel’s cache to optimize performance:

    $translator->setCache(function () {
        return Cache::remember('translations', now()->addHours(1), function () {
            return $this->loadTranslations();
        });
    });
    

Gotchas and Tips

Common Pitfalls

  1. Missing Translation Files

    • Issue: trans() returns the key instead of a value if the file or key is missing.
    • Fix: Enable strict mode in config/translator.php:
      'strict' => true,
      
      Or check existence first:
      if ($translator->has('messages.welcome')) {
          $translator->trans('messages.welcome');
      }
      
  2. Locale Not Found

    • Issue: Using a locale not defined in config/translator.php throws an exception.
    • Fix: Add the locale to the config or handle the exception:
      try {
          $translator->setLocale('pt-BR');
      } catch (\InvalidArgumentException $e) {
          $translator->setLocale('en');
      }
      
  3. File Path Issues

    • Issue: Translations not loading due to incorrect paths.
    • Fix: Verify paths in config/translator.php and ensure files are in the correct structure:
      resources/
      └── lang/
          ├── en/
          │   └── messages.php
          └── es/
              └── messages.php
      
  4. Interpolation Errors

    • Issue: Placeholders not being replaced (e.g., :name remains as-is).
    • Fix: Ensure the translation string uses the correct syntax (e.g., :name not {name} unless using transChoice).
  5. Loader Conflicts

    • Issue: Custom loaders not being picked up.
    • Fix: Ensure the loader is properly registered in config/translator.php and implements LoaderInterface.
  6. Case Sensitivity

    • Issue: Translation keys are case-sensitive (e.g., messages.Welcome vs. messages.welcome).
    • Fix: Standardize key casing in your translation files.
  7. Fallback Not Working

    • Issue: Fallback locales not triggering.
    • Fix: Verify the fallback chain in config/translator.php and ensure the fallback locales are defined.
  8. Performance with Large Catalogs

    • Issue: Slow loading times with many translation files.
    • Fix: Implement caching (e.g., Redis) or use a database-backed loader.

Debugging Tips

  1. Log Missing Keys Add a listener to log missing translations:

    $translator->setMissingListener(function ($locale, $group, $key) {
        Log::warning("Missing translation: {$locale}.{$group}.{$key}");
    });
    
  2. Check Loaded Translations Dump the loaded translations for debugging:

    dd($translator->getLoader()->getCatalogue($locale)->all());
    
  3. Validate Translation Files Use a JSON/YAML linter to catch syntax errors before runtime.

  4. Test Locale Switching Verify locale switching works as expected:

    $translator->setLocale('es');
    assert($translator->getLocale() === 'es');
    

Configuration Quirks

  1. Default Locale

    • The default locale is set in config/translator.php under 'locale'. Ensure it matches your app’s default.
  2. Loader Priorities

    • Loaders are executed in the order defined in config/translator.php. The first loader to return a translation wins.
  3. **

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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky