Weave 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

Localisator Laravel Package

avris/localisator

Laravel package for localization: detect current locale, resolve language from request/user settings, and manage locale switching. Helps build multilingual apps with clean locale handling and integration points for routes, middleware, and views.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require avris/localisator
    

    Publish the config file (if needed):

    php artisan vendor:publish --provider="Avris\Localisator\LocalisatorServiceProvider"
    
  2. Basic Configuration Edit config/localisator.php to define your locales and default locale:

    'locales' => [
        'en' => 'English',
        'fr' => 'Français',
    ],
    'default' => 'en',
    
  3. First Use Case: Localized Messages Define translations in resources/lang/{locale}/messages.php:

    // resources/lang/en/messages.php
    return [
        'welcome' => 'Welcome to our app!',
    ];
    
    // resources/lang/fr/messages.php
    return [
        'welcome' => 'Bienvenue sur notre application!',
    ];
    

    Use in Blade:

    {{ __('messages.welcome') }}
    

    Or in PHP:

    $message = trans('messages.welcome');
    

Implementation Patterns

1. Dynamic Locale Switching

  • Middleware: Use LocalisatorMiddleware to set locale from URL, session, or headers.
    // app/Http/Kernel.php
    protected $middlewareGroups = [
        'web' => [
            // ...
            \Avris\Localisator\Http\Middleware\Localisator::class,
        ],
    ];
    
  • Route Parameters: Extract locale from route (e.g., /{locale}/dashboard).
    Route::get('/{locale}/dashboard', [Controller::class, 'dashboard']);
    

2. Fallback Chains

Configure fallback locales in config/localisator.php:

'fallbacks' => [
    'fr' => ['en'], // Fallback to English if French translation is missing
],

Use in code:

$message = trans('messages.welcome', [], null, 'fr'); // Automatically falls back to 'en'

3. Custom Translation Sources

Extend the package to load translations from databases or APIs:

// app/Providers/AppServiceProvider.php
use Avris\Localisator\TranslationLoader;

public function boot()
{
    Localisator::extend('db', function ($locale) {
        return new DatabaseTranslationLoader($locale);
    });
}

Use in Blade:

{{ __('messages.welcome', [], 'db') }}

4. Validation Messages

Localize validation errors by prefixing keys:

$validator = Validator::make($request->all(), [
    'email' => 'required|email',
]);
$validator->setAttributeNames([
    'email' => 'user.email', // Translates to 'validation.user.email'
]);

Define translations:

// resources/lang/en/validation.php
return [
    'user.email.required' => 'The user email field is required.',
];

5. JavaScript Localization

Publish assets and use in JS:

php artisan vendor:publish --tag=localisator-assets

Load translations in Blade:

<script>
    window.translations = @json(__('js'));
</script>

Define JS translations:

// resources/lang/en/js.php
return [
    'confirm_delete' => 'Are you sure you want to delete this?',
];

Gotchas and Tips

Pitfalls

  1. Caching Issues

    • Clear translation cache after adding new locales or translations:
      php artisan view:clear
      php artisan cache:clear
      
    • Disable caching in config/localisator.php during development:
      'cache' => env('APP_DEBUG') ? false : true,
      
  2. Locale Negotiation Conflicts

    • Ensure middleware and route parameters align. For example, avoid:
      // Route: /{locale}/dashboard
      // Middleware sets locale from session, but route parameter overrides it.
      
    • Fix: Use Localisator::setLocale() explicitly in middleware or controllers.
  3. Missing Fallback Handling

    • If a translation is missing and no fallback is configured, trans() returns the key instead of throwing an error.
    • Tip: Use trans_choice() for pluralization or validate translations exist:
      if (!trans()->has('messages.welcome')) {
          throw new \RuntimeException("Translation missing for 'messages.welcome'");
      }
      
  4. Blade Cache Conflicts

    • If using @lang directives, ensure the locale is set before rendering:
      @php
          app('localisator')->setLocale('fr');
      @endphp
      <p>@lang('messages.welcome')</p>
      

Debugging Tips

  1. Check Loaded Locale
    dd(app('localisator')->getLocale());
    
  2. Inspect Fallback Chain
    dd(app('localisator')->getFallbacks());
    
  3. Log Missing Translations Override the missing method in a custom translator:
    use Avris\Localisator\Localisator;
    
    Localisator::macro('missing', function ($key) {
        \Log::warning("Missing translation: {$key}");
        return $key;
    });
    

Extension Points

  1. Custom Loaders Implement Avris\Localisator\Contracts\TranslationLoader for non-file-based sources (e.g., API, DB):

    class ApiTranslationLoader implements TranslationLoader {
        public function load($locale, $group, $key) {
            return Api::getTranslation($locale, $group, $key);
        }
    }
    
  2. Locale Detection Logic Override the detectLocale method in a custom middleware:

    public function handle($request, Closure $next) {
        $locale = $request->header('X-Locale') ?? 'en';
        app('localisator')->setLocale($locale);
        return $next($request);
    }
    
  3. Post-Translation Hooks Use events to modify translations dynamically:

    // config/localisator.php
    'events' => [
        'Avris\Localisator\Events\TranslationLoaded' => [
            \App\Listeners\ModifyTranslation::class,
        ],
    ];
    

Performance Tips

  1. Preload Translations Use trans()->getLoader()->load() to preload critical translations in a service provider:
    public function boot() {
        trans()->getLoader()->load('en', 'messages');
    }
    
  2. Disable Unused Locales Set cache to true in production and only include necessary locales in config/localisator.php.
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.
coleus/frame
thtg88/journalism
filagora/filagora-ai-forums
rlacerda83/query-parser
socialdept/atp-orm
cboxdk/laravel-assistant-client
socialdept/atp-resolver
socialdept/tenant-domains
tautvydasr/blade-class-names
socialdept/color-scales
maherelgamil/controller
coleus/widgets
coleus/table
coleus/users
coleus/music
coleus/health
coleus/calendar
coleus/notes
coleus/support
coleus/settings