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

Laravel Localizer Laravel Package

devwizardhq/laravel-localizer

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require devwizardhq/laravel-localizer
    php artisan localizer:install
    

    Follow prompts to configure default locales (e.g., en, fr).

  2. First Translation Use Add a translation key in resources/lang/en/messages.php:

    return [
        'welcome' => 'Welcome, :name!',
    ];
    

    Use it in Laravel:

    __('messages.welcome', ['name' => 'John']);
    
  3. Frontend Integration (React/Vue) Generate TypeScript types and JSON assets:

    php artisan localizer:generate
    

    Import in your frontend:

    import { translations } from '@/localizer/translations';
    console.log(translations.en.messages.welcome); // "Welcome, :name!"
    
  4. First Auto-Translation Run Google Translate auto-fill for missing keys:

    php artisan localizer:translate --locale=fr
    

Where to Look First

  • Config File: config/localizer.php (adjust locales, Google Translate API key, and output paths).
  • Generated Assets: resources/js/localizer/ (TypeScript types and JSON files).
  • Middleware: app/Http/Middleware/LocalizerMiddleware.php (handles locale detection and injection).
  • Artisan Commands: localizer:generate, localizer:translate, localizer:scan.

First Use Case: Localized SPA

  1. Backend:

    • Define translations in resources/lang/.
    • Use __() in Blade/Laravel logic.
    • Generate assets with php artisan localizer:generate.
  2. Frontend (React Example):

    // Use the generated types
    const { t } = useTranslation(); // Hook from your i18n library (e.g., i18next)
    const welcomeMessage = t('messages.welcome', { name: 'Jane' });
    

Implementation Patterns

Core Workflow

  1. Translation Management:

    • Scan: Use php artisan localizer:scan to auto-discover keys from __() calls in Blade/Laravel code.
    • Translate: Auto-fill missing keys with php artisan localizer:translate --locale=es.
    • Validate: Ensure keys are consistent across locales with php artisan localizer:validate.
  2. Frontend Integration:

    • TypeScript Generation: Run php artisan localizer:generate to output:
      • translations.ts (typed translations object).
      • translations.json (runtime data for your i18n library).
    • Dynamic Loading: Use the LocalizerMiddleware to inject the current locale’s translations into your SPA’s context (e.g., via Inertia or API responses).
  3. RTL Support:

    • Configure RTL languages in config/localizer.php:
      'rtl_locales' => ['ar', 'he'],
      
    • Use the isRtl() helper in your frontend CSS/JS:
      if (localizer.isRtl()) {
        document.body.classList.add('rtl');
      }
      

Integration Tips

  1. With Inertia.js:

    • Share translations via Laravel’s share method in app/Http/Middleware/HandleInertiaRequests.php:
      public function share(Request $request): array
      {
          return array_merge(parent::share($request), [
              'localizer' => [
                  'locale' => app()->getLocale(),
                  'translations' => json_encode(__('json')),
              ],
          ]);
      }
      
    • Access in React:
      const { localizer } = page.props;
      
  2. With Vue/i18next:

    • Initialize i18next dynamically:
      import translations from '@/localizer/translations';
      i18n.init({
        resources: {
          en: { translation: translations.en },
          fr: { translation: translations.fr },
        },
      });
      
  3. Vendor Translations:

    • Auto-include translations from packages like laravel-framework:
      // config/localizer.php
      'vendor_locales' => [
          'laravel-framework' => ['en', 'es'],
      ],
      
  4. Custom Scanning:

    • Extend the scanner to support custom __() patterns:
      // app/Providers/LocalizerServiceProvider.php
      Localizer::extendScanner(function (Scanner $scanner) {
          $scanner->addPattern('/__\("([^"]+)"\)/', 1);
      });
      

Performance Optimization

  1. Build-Time Generation:

    • Run php artisan localizer:generate during your build process (e.g., in vite.config.ts or webpack.mix.js):
      mix.after(() => {
          require('laravel-mix').run('localizer:generate');
      });
      
  2. Caching:

    • Enable in-memory caching for faster scans:
      // config/localizer.php
      'cache' => [
          'enabled' => true,
          'driver' => 'file', // or 'redis'
      ],
      
  3. Lazy Loading:

    • Load translations dynamically for large apps:
      // Only load the current locale's translations
      const { locale } = localizer;
      const currentTranslations = translations[locale];
      

Gotchas and Tips

Pitfalls

  1. Key Mismatches:

    • Issue: Keys defined in Laravel (__('messages.welcome')) may not match frontend usage (t('messages.welcome')).
    • Fix: Run php artisan localizer:validate to catch inconsistencies. Use the --fix flag to auto-correct:
      php artisan localizer:validate --fix
      
  2. Google Translate API Limits:

    • Issue: Auto-translation may fail due to API quotas or missing keys.
    • Fix:
      • Set a high quota in config/localizer.php:
        'google_translate' => [
            'enabled' => true,
            'api_key' => env('GOOGLE_TRANSLATE_API_KEY'),
            'max_results' => 1000, // Increase as needed
        ],
        
      • Manually translate critical keys.
  3. TypeScript Conflicts:

    • Issue: Generated TypeScript may conflict with existing types.
    • Fix: Exclude specific keys in config/localizer.php:
      'typescript' => [
          'exclude_keys' => ['password.*', 'api.*'],
      ],
      
  4. Middleware Overhead:

    • Issue: LocalizerMiddleware may slow down API routes.
    • Fix: Exclude non-localized routes:
      // app/Http/Kernel.php
      protected $middleware = [
          // ...
          \DevWizardHQ\Localizer\Http\Middleware\LocalizerMiddleware::class,
      ];
      
      protected $middlewareGroups = [
          'web' => [
              // ...
          ],
          'api' => [
              // Exclude LocalizerMiddleware for API
          ],
      ];
      

Debugging

  1. Log Translation Issues:

    • Enable debug logging in config/localizer.php:
      'debug' => [
          'enabled' => true,
          'log_path' => storage_path('logs/localizer.log'),
      ],
      
    • Check logs for missing keys or scan errors.
  2. Verify Generated Assets:

    • Ensure php artisan localizer:generate outputs files to the correct path (default: resources/js/localizer/).
    • Check for TypeScript errors in your IDE after generation.
  3. Locale Detection:

    • Debug locale detection in LocalizerMiddleware:
      // app/Http/Middleware/LocalizerMiddleware.php
      public function handle($request, Closure $next) {
          \Log::info('Detected locale:', [$request->locale(), $request->header('x-localizer-locale')]);
          return $next($request);
      }
      

Extension Points

  1. Custom Translator:

    • Replace Google Translate with a custom translator:
      Localizer::extendTranslator(function () {
          return new CustomTranslator();
      });
      
  2. Post-Processing:

    • Modify generated translations with a callback:
      Localizer::afterGenerate(function (array $translations) {
          $translations['en']['custom'] = 'dynamic value';
          return $translations;
      });
      
  3. Custom Scanner:

    • Add support for custom __() patterns (e.g., __m('module.key')):
      Localizer::extendScanner(function (Scanner $scanner) {
          $scanner->addPattern('/__m\(\'([^\']+)\'\)/', 1);
      });
      
  4. Webpack/Vite Plugin:

    • Integrate with your frontend build tool:
      // vite.config.ts
      import { defineConfig } from 'vite';
      
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui