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

Locales Laravel Package

laravel-lang/locales

Locale data package for Laravel Lang. Provides up-to-date locale definitions you can use across your Laravel apps, with documentation for installation and contribution guidelines. MIT licensed.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require laravel-lang/locales
    

    Publish the config (optional):

    php artisan vendor:publish --provider="LaravelLang\Locales\LocalesServiceProvider" --tag="locales-config"
    
  2. First Use Case: Fetch the current locale’s metadata (e.g., for a language selector dropdown):

    use LaravelLang\Locales\Facades\Locales;
    
    $currentLocale = Locales::getCurrent(); // Returns LocaleData object
    echo $currentLocale->name; // e.g., "English"
    echo $currentLocale->native; // e.g., "English" (localized name)
    echo $currentLocale->direction; // "ltr" or "rtl"
    
  3. Key Facade Methods:

    • Locales::get($locale): Get a LocaleData object for a specific locale (e.g., Locales::get('fr_CA')).
    • Locales::available(): List all supported locales (as LocaleData collection).
    • Locales::installed(): List installed locales (checks app.php config).
    • Locales::info($locale): Detailed metadata (e.g., country, currency, scripts).
  4. Blade Integration:

    @php
        $locale = LaravelLang\Locales\Facades\Locales::get('en_CA');
    @endphp
    <select>
        <option value="{{ $locale->code }}">{{ $locale->name }} ({{ $locale->country->name }})</option>
    </select>
    

Implementation Patterns

Core Workflows

  1. Dynamic Locale Selection:

    • Use Locales::getCurrent() in middleware to set user-specific locales:
      public function handle($request, Closure $next) {
          $locale = Locales::get($request->input('locale', app()->getLocale()));
          app()->setLocale($locale->code);
          return $next($request);
      }
      
  2. Region-Specific Features:

    • Filter locales by country/currency for targeted UIs:
      $canadianLocales = Locales::available()
          ->where('country.code', 'CA')
          ->values('code'); // ['en_CA', 'fr_CA']
      
  3. Form Validation:

    • Validate locale codes against supported options:
      use LaravelLang\Locales\Facades\Locales;
      
      $validator = Validator::make($request->all(), [
          'locale' => ['required', function ($attribute, $value, $fail) {
              if (!Locales::available()->contains('code', $value)) {
                  $fail('Invalid locale.');
              }
          }],
      ]);
      
  4. RTL/LTR Detection:

    • Toggle CSS/JS based on script direction:
      $direction = Locales::get(app()->getLocale())->direction;
      view()->share('isRtl', $direction === 'rtl');
      
  5. Multi-Tenant Localization:

    • Store tenant-specific locales in a tenants table and fetch dynamically:
      $tenantLocale = Locales::get($tenant->locale);
      $tenantCurrency = $tenantLocale->currency->code;
      

Integration Tips

  • Laravel Validation: Extend Illuminate\Validation\Rules\In to validate against installed locales:

    use LaravelLang\Locales\Facades\Locales;
    
    $rule = new In(Locales::installed()->pluck('code')->toArray());
    
  • Blade Directives: Create a custom directive for locale-aware content:

    Blade::directive('locale', function ($locale) {
        $localeData = Locales::get($locale);
        return "<?php echo \$localeData->name; ?>";
    });
    

    Usage:

    @locale('fr_CA') <!-- Outputs "French (Canada)" -->
    
  • API Responses: Attach locale metadata to API responses:

    return response()->json([
        'data' => $data,
        'locale' => Locales::get(app()->getLocale())->toArray(),
    ]);
    
  • Testing: Mock locales in tests:

    Locales::shouldReceive('get')
        ->with('en_CA')
        ->andReturn(new LocaleData(['code' => 'en_CA', 'name' => 'Test Locale']));
    
  • Configuration: Override defaults in config/locales.php:

    'with_countries' => true,
    'with_currencies' => true,
    'with_protects' => false, // Disable protected locales (e.g., 'en_US')
    

Gotchas and Tips

Pitfalls

  1. Null Locale Handling:

    • Always validate locales before passing to Locales::get():
      $locale = $request->input('locale', app()->getLocale());
      if (!Locales::available()->contains('code', $locale)) {
          abort(400, 'Invalid locale');
      }
      
    • Fix: Use Locales::get($locale ?? app()->getLocale()) to avoid null errors (see v2.9.2).
  2. Performance:

    • Caching Locales::available() in a service provider:
      public function boot() {
          $this->app->singleton('locales.available', function () {
              return Locales::available();
          });
      }
      
    • Tip: Disable with_countries/with_currencies if unused to reduce memory usage.
  3. Locale Code Mismatches:

    • Laravel’s app()->setLocale('en') vs. Locales::get('en_US'):
      • Use Locales::get(app()->getLocale()) to resolve the current locale’s full metadata.
    • Tip: Normalize locale codes early in your app (e.g., enen_US).
  4. Protected Locales:

    • Locales::installed($withProtects = false) excludes protected locales (e.g., en_US) by default.
    • Fix: Pass $withProtects = true if you need to include them.
  5. Deprecations:

    • Locales::getDefault() is an alias for Locales::getCurrent() (v2.2.0+).
    • Locale class renamed to LocaleData (v1.4.0+).

Debugging

  1. Locale Not Found:

    • Check if the locale is installed in config/app.php under locales.
    • Verify the locale exists in Locales::available():
      dd(Locales::available()->pluck('code'));
      
  2. Country/Currency Missing:

    • Ensure with_countries/with_currencies are enabled in config.
    • Workaround: Access raw data via Locales::raw()->get($locale).
  3. Direction Issues:

    • Test with Locales::get('ar') (RTL) and Locales::get('en') (LTR):
      dd(Locales::get('ar')->direction); // Should return 'rtl'
      

Extension Points

  1. Custom Locale Data:

    • Extend LocaleData for app-specific fields:
      class ExtendedLocaleData extends \LaravelLang\Locales\LocaleData {
          public function getTimezone() {
              return $this->customData['timezone'] ?? 'UTC';
          }
      }
      
    • Override the facade to use your class:
      Locales::macro('get', function ($locale) {
          return new ExtendedLocaleData(Locales::raw()->get($locale));
      });
      
  2. Dynamic Locale Loading:

    • Load locales from a database or API:
      Locales::macro('getFromDb', function ($code) {
          $dbLocale = DB::table('locales')->where('code', $code)->first();
          return new LocaleData($dbLocale ?? []);
      });
      
  3. Event Listeners:

    • Trigger actions when the locale changes:
      event(new LocaleChanged($oldLocale, $newLocale));
      
  4. Testing Utilities:

    • Create a test helper:
      if (!function_exists('mock_locale')) {
          function mock_locale($code, array $data = []) {
              Locales::shouldReceive('get')
                  ->with($code)
                  ->andReturn(new LocaleData(array_merge($data, ['code' => $code])));
          }
      }
      

Pro Tips

  1. Locale-Aware Sorting:
    use LaravelLang\Locales\Facades\Locales;
    
    $sortedLocales = Locales::available()
        ->sortBy(function ($locale) {
            return Locales::get($locale->
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport