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

derafu/translation

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require derafu/translation
    

    Add the service provider to config/app.php:

    'providers' => [
        // ...
        Derafu\Translation\TranslationServiceProvider::class,
    ],
    
  2. Basic Usage: Load translations via the facade:

    use Derafu\Translation\Facades\Translation;
    
    // Load a translation file (e.g., `resources/lang/en/messages.php`)
    Translation::load('en', 'messages', require base_path('resources/lang/en/messages.php'));
    
    // Translate a key
    $translated = Translation::get('messages.welcome');
    
  3. First Use Case:

    • Replace hardcoded strings in a controller/view with dynamic translations.
    • Example:
      $greeting = Translation::get('messages.greeting', ['name' => 'John']);
      return view('welcome', compact('greeting'));
      

Implementation Patterns

Workflows

  1. File-Based Translations:

    • Organize translations in resources/lang/{locale}/ (e.g., en/messages.php).
    • Use nested arrays for hierarchical keys:
      return [
          'welcome' => 'Welcome, :name!',
          'errors'  => [
              'invalid' => 'The :attribute is invalid.',
          ],
      ];
      
  2. Dynamic Loading:

    • Load translations on-demand (e.g., from a database or API):
      $customTranslations = $this->fetchTranslationsFromDB();
      Translation::load('en', 'custom', $customTranslations);
      
  3. Fallback Chains:

    • Set fallback locales for missing keys:
      Translation::setFallbacks(['en', 'es']);
      Translation::get('messages.welcome'); // Falls back to 'en' if 'es' key is missing.
      
  4. View Integration:

    • Use the @lang directive in Blade:
      @lang('messages.welcome', ['name' => $user->name])
      
  5. Exception Handling:

    • Enable translation exceptions for debugging:
      Translation::enableExceptions();
      Translation::get('nonexistent.key'); // Throws Derafu\Translation\TranslationException.
      

Integration Tips

  • Laravel Localization: Combine with laravel-localization for route-based locale switching.
  • Validation Messages: Override default validation messages:
    Translation::load('en', 'validation', [
        'required' => 'The :attribute field is required.',
    ]);
    
  • Testing: Mock translations in tests:
    Translation::fake()->setTranslations('en', ['test' => 'Mocked']);
    $this->assertEquals('Mocked', Translation::get('test'));
    

Gotchas and Tips

Pitfalls

  1. Missing Files:

    • If resources/lang/{locale}/ doesn’t exist, create it or ensure files are loaded programmatically.
    • Fix: Use Translation::load() explicitly for custom paths.
  2. Caching:

    • Translations aren’t cached by default. For performance, cache loaded translations:
      Cache::remember('translations-en', 60, function () {
          return Translation::getAll();
      });
      
  3. Locale Switching:

    • Locale changes (e.g., via middleware) won’t auto-reload translations. Reload them manually:
      app()->setLocale('es');
      Translation::load('es', 'messages', ...);
      
  4. Exception Overhead:

    • Enabling exceptions (Translation::enableExceptions()) adds overhead. Disable in production:
      if (app()->environment('production')) {
          Translation::disableExceptions();
      }
      

Debugging

  • Missing Keys:

    • Check for typos in keys or missing files. Use Translation::getAll() to inspect loaded translations.
    • Enable exceptions temporarily to catch missing keys early.
  • Fallback Issues:

    • Verify fallback locales are set and translations exist in fallback files:
      Translation::setFallbacks(['en']);
      Translation::get('es.messages.welcome'); // Falls back to 'en.messages.welcome'.
      

Extension Points

  1. Custom Loaders:

    • Extend Derafu\Translation\Loaders\LoaderInterface to support non-file sources (e.g., databases):
      class DatabaseLoader implements LoaderInterface {
          public function load(string $locale, string $group, array $translations) {
              // Save to DB...
          }
      }
      
  2. Macros:

    • Add custom methods to the facade:
      Translation::macro('plural', function ($key, $count, array $replace = []) {
          $key = $count === 1 ? "{$key}_singular" : "{$key}_plural";
          return Translation::get($key, $replace);
      });
      
  3. Event Listeners:

    • Listen for translation events (e.g., TranslationLoaded):
      Translation::addListener('TranslationLoaded', function ($locale, $group) {
          Log::info("Loaded translations for {$locale}.{$group}");
      });
      
  4. Locale-Specific Logic:

    • Use middleware to load locale-specific translations:
      public function handle($request, Closure $next) {
          $locale = $request->segment(1);
          Translation::load($locale, 'messages', ...);
          return $next($request);
      }
      
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