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 Setup

  1. Installation:

    composer require laravel-lang/locales
    

    Publish the config file (if needed):

    php artisan vendor:publish --provider="LaravelLang\Locales\LocalesServiceProvider" --tag="locales-config"
    
  2. First Use Case: Check available locales in your app:

    use LaravelLang\Locales\Facades\Locales;
    
    $locales = Locales::available(); // Collection of all supported locales
    $currentLocale = Locales::getCurrent(); // Current app locale
    
  3. Key Files:

    • config/locales.php: Configuration for enabled locales, countries, and currencies.
    • app/Providers/AppServiceProvider.php: Register the package (auto-done on install).

Implementation Patterns

Core Workflows

1. Locale Detection & Switching

  • Dynamic Detection:
    $locale = Locales::detect(); // Auto-detects from browser/headers
    Locales::set($locale); // Updates the current locale
    
  • Fallback Chain:
    $fallback = Locales::getFallback('fr-CA'); // Returns 'fr' if 'fr-CA' isn't installed
    

2. Integration with Laravel Features

  • Translation System:
    // Use with Laravel's built-in translation
    $translated = trans('messages.welcome', [], null, 'fr'); // French translation
    
  • Locale-Aware Formatting:
    use LaravelLang\Locales\Facades\Locales;
    
    $localeData = Locales::get('en-US');
    echo $localeData->currencySymbol; // '$'
    echo $localeData->dateFormat;     // 'm/d/Y'
    

3. RTL (Right-to-Left) Support

  • Check if a locale is RTL:
    if (Locales::get('ar-SA')->direction === 'rtl') {
        // Load RTL-specific CSS/JS
    }
    

4. Asset Management

  • Load locale-specific assets (e.g., flags):
    $flagUrl = asset("flags/{$localeData->code}.svg");
    

5. API Responses

  • Set locale in API responses:
    return response()->json($data, 200, [], [
        'Accept-Language' => Locales::getCurrent()->code,
    ]);
    

Advanced Patterns

Custom Locale Data

Extend the LocaleData class to add custom properties:

use LaravelLang\Locales\LocaleData;

class CustomLocaleData extends LocaleData
{
    public function getCustomProperty()
    {
        return $this->customData ?? null;
    }
}

Middleware for Locale Routing

use LaravelLang\Locales\Facades\Locales;

class SetLocaleMiddleware
{
    public function handle($request, Closure $next)
    {
        $locale = $request->segment(1);
        if (Locales::has($locale)) {
            Locales::set($locale);
            app()->setLocale($locale);
        }
        return $next($request);
    }
}

Dynamic Fallback Logic

$locale = Locales::get('fr-CA');
if (!$locale->installed) {
    $locale = Locales::getFallback($locale->code); // Falls back to 'fr'
}

Locale-Specific Views

// In Blade
@if (Locales::getCurrent()->direction === 'rtl')
    <link rel="stylesheet" href="{{ asset('css/rtl.css') }}">
@endif

Gotchas and Tips

Pitfalls

  1. Configuration Quirks:

    • Countries/Currencies Disabled by Default: Ensure you enable them in config/locales.php if needed:
      'with_countries' => true,
      'with_currencies' => true,
      
    • Locale Not Found: Always check if a locale exists before using it:
      if (Locales::has('xx-XX')) {
          // Safe to use
      }
      
  2. Performance:

    • Avoid Repeated Calls: Cache locale data if accessed frequently:
      $locale = cache()->remember("locale.{$code}", now()->addHours(1), fn() => Locales::get($code));
      
  3. RTL Issues:

    • CSS Conflicts: Ensure your CSS framework (e.g., Bootstrap, Tailwind) supports RTL. Test with:
      if (Locales::getCurrent()->direction === 'rtl') {
          app()->setLocale('ar'); // Force RTL for testing
      }
      
  4. Fallback Logic:

    • Unexpected Fallbacks: Verify fallback chains manually:
      $fallback = Locales::getFallback('fr-CA'); // Should return 'fr', not 'en'
      
  5. Artisan Commands:

    • Locale-Specific Commands: Some commands (e.g., artisan about) may not respect the current locale. Override them if needed.

Debugging Tips

  1. Inspect Locale Data:

    dd(Locales::get('en-US')->toArray());
    
  2. Check Installed Locales:

    Locales::installed()->pluck('code'); // List all installed locales
    
  3. Enable Debug Mode:

    Locales::setDebug(true); // Logs locale-related operations
    
  4. Validate Config:

    php artisan config:clear
    php artisan optimize:clear
    

Extension Points

  1. Add Custom Locales:

  2. Override Locale Data:

    Locales::extend('custom', function () {
        return new CustomLocaleData([
            'code' => 'custom',
            'name' => 'Custom Locale',
            'direction' => 'ltr',
        ]);
    });
    
  3. Integrate with Translation Services:

    // Example: Auto-translate missing keys via API
    app()->bind('translator', function ($app) {
        $trans = new Translator($app['view'], $app['files']);
        $trans->setTranslator(new ApiTranslator($trans));
        return $trans;
    });
    
  4. Locale-Specific Database Handling:

    // Example: Store locale in user model
    $user->locale = Locales::getCurrent()->code;
    $user->save();
    
  5. Testing:

    • Use Locales::fake() for isolated tests:
      Locales::fake([
          'en-US' => new LocaleData(['code' => 'en-US', 'name' => 'Test English']),
      ]);
      

Pro Tips

  1. Locale-Specific URLs:

    Route::get('/{locale}/posts', function ($locale) {
        Locales::set($locale);
        return view('posts.index');
    })->where('locale', Locales::available()->pluck('code')->join('|'));
    
  2. Dynamic Language Switcher:

    <select onchange="window.location.href=this.value">
        @foreach(Locales::available() as $locale)
            <option value="{{ route('set-locale', $locale->code) }}"
                    {{ Locales::getCurrent()->code === $locale->code ? 'selected' : '' }}>
                {{ $locale->native }}
            </option>
        @endforeach
    </select>
    
  3. Locale-Aware Validation:

    use LaravelLang\Locales\Facades\Locales;
    
    $validator = Validator::make($request->all(), [
        'phone' => 'required|phone:' . Locales::getCurrent()->code,
    ]);
    
  4. Performance Optimization:

    • Preload locales in a service provider:
      public function boot()
      {
          Locales::available(); // Loads all locales once
      }
      
  5. Locale-Specific Notifications:

    Notification::route('mail', $user->email)
                ->locale(Locales::getCurrent()->code)
                ->notify(new OrderShipped($order));
    

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.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai