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

Locale Laravel Package

php-standard-library/locale

PHP Standard Library Locale component providing locale-aware formatting and parsing utilities. Helps handle language/region settings, localized dates, numbers, and other internationalization tasks in PHP apps with a lightweight, straightforward API.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require php-standard-library/locale
    

    No additional configuration is required—use the Locale class directly.

  2. First Use Case: Validate and Normalize a Locale Replace raw string checks with type-safe validation:

    use PhpStandardLibrary\Locale\Locale;
    
    // In a controller or service
    $rawLocale = request()->input('locale', 'en_US');
    $locale = Locale::fromString($rawLocale);
    
    if ($locale->isValid()) {
        app()->setLocale($locale->toString()); // Normalized (e.g., 'en_US')
        // Proceed with i18n logic
    } else {
        abort(422, 'Invalid locale format. Use e.g., "en_US".');
    }
    
  3. Key Methods to Explore First

    • Locale::fromString(string $locale) → Creates a validated Locale object.
    • $locale->isValid() → Checks if the locale is valid.
    • $locale->toString() → Returns the normalized BCP 47 string (e.g., en_US).
    • Locale::isValid(string $locale) → Static validator for quick checks.
    • $locale->getLanguage() / $locale->getRegion() → Extract components.
  4. Where to Look Next

    • Documentation: PHP Standard Library Docs for advanced use cases (e.g., private-use tags, extensions).
    • Source Code: Locale.php to understand parsing logic or extend behavior.

Implementation Patterns

Core Workflows

1. Request Handling

Pattern: Parse and validate locales from user input (headers, forms, cookies). Example:

// Middleware to set the app locale from Accept-Language header
public function handle(Request $request, Closure $next) {
    $headerLocale = $request->header('Accept-Language', config('app.locale'));
    $locale = Locale::fromString($headerLocale);

    if ($locale->isValid()) {
        app()->setLocale($locale->toString());
    }

    return $next($request);
}

2. Validation Layer

Pattern: Replace regex or manual checks with Locale validation. Example:

// Form Request validation
public function rules() {
    return [
        'locale' => ['required', function ($attribute, $value, $fail) {
            if (!Locale::isValid($value)) {
                $fail('The :attribute must be a valid locale (e.g., en_US).');
            }
        }],
    ];
}

3. Domain Modeling

Pattern: Use Locale as a value object in Eloquent models or DTOs. Example:

// Eloquent model with typed locale
class User extends Model {
    protected $casts = [
        'locale' => Locale::class, // Automatically validates on set
    ];

    public function setLocaleAttribute(string $locale) {
        $this->attributes['locale'] = Locale::fromString($locale)->toString();
    }
}

4. API/GraphQL Inputs

Pattern: Validate locale inputs in API schemas or GraphQL directives. Example (Lumen/Laravel API):

use PhpStandardLibrary\Locale\Locale;

$validator = Validator::make($request->all(), [
    'user_locale' => ['required', function ($value) {
        return Locale::isValid($value);
    }],
]);

5. Localization Services

Pattern: Normalize locales before passing to Laravel’s trans() or third-party i18n libraries. Example:

$locale = Locale::fromString($user->locale)->toString();
$translation = trans('messages.welcome', [], null, $locale);

Integration Tips

Laravel-Specific Integrations

  1. Service Providers Bind the Locale class to the container for dependency injection:

    $app->bind(Locale::class, function () {
        return Locale::fromString(config('app.locale'));
    });
    
  2. Middleware for Locale Routing Dynamically set the locale based on route parameters:

    public function handle($request, Closure $next, $locale) {
        $normalized = Locale::fromString($locale)->toString();
        app()->setLocale($normalized);
        return $next($request);
    }
    

    Route Definition:

    Route::middleware('set.locale')->group(function () {
        Route::get('/{locale}/dashboard', [DashboardController::class, 'index']);
    });
    
  3. Testing Use Locale in feature tests to assert locale handling:

    public function test_locale_validation() {
        $response = $this->post('/profile', ['locale' => 'invalid']);
        $response->assertSessionHasErrors('locale');
    
        $response = $this->post('/profile', ['locale' => 'en_US']);
        $response->assertSessionHasNoErrors();
    }
    

Performance Considerations

  • Caching: Cache normalized locale strings in middleware or services if parsing is a bottleneck:
    $locale = cache()->remember("locale.{$rawLocale}", now()->addHours(1), function () use ($rawLocale) {
        return Locale::fromString($rawLocale);
    });
    
  • Bulk Validation: For APIs processing many locales (e.g., bulk user updates), validate in batches:
    $locales = ['en_US', 'fr_FR', 'invalid'];
    $validLocales = array_filter($locales, fn($l) => Locale::isValid($l));
    

Frontend Integration

  • JavaScript: Normalize locales client-side before sending to Laravel:
    // Example: Normalize 'en-US' to 'en_US' before API call
    const normalizedLocale = locale.replace(/-/g, '_');
    await axios.post('/api/profile', { locale: normalizedLocale });
    
  • Vue/React: Use the package in full-stack apps by including the TypeScript types (if available) or documenting the expected format.

Gotchas and Tips

Pitfalls

  1. Case Sensitivity

    • Gotcha: Locale::fromString('EN_US') may fail if the package enforces lowercase language codes (e.g., en_US).
    • Fix: Normalize input first:
      $locale = Locale::fromString(strtolower($rawLocale));
      
  2. Private-Use and Extension Tags

    • Gotcha: Locales like sr-Latn-RS (Serbian Latin script) or und (undetermined) may not be handled by default.
    • Fix: Extend the package or wrap calls:
      try {
          $locale = Locale::fromString('sr-Latn-RS');
      } catch (InvalidArgumentException $e) {
          $locale = Locale::fromString('sr'); // Fallback
      }
      
  3. Database Storage

    • Gotcha: Storing Locale objects directly in databases may fail if the column type is string but the object isn’t cast properly.
    • Fix: Use accessors/mutators or cast the attribute:
      protected $casts = [
          'locale' => 'string', // Store as string, validate on set
      ];
      
  4. Locale Fallbacks

    • Gotcha: Fallback logic (e.g., en_USen) may not match Laravel’s default fallback chain.
    • Fix: Implement custom fallback logic:
      $locale = Locale::fromString($userLocale);
      if (!$locale->isValid()) {
          $locale = Locale::fromString(config('app.fallback_locale'));
      }
      
  5. Package Updates

    • Gotcha: Future versions may change parsing rules (e.g., stricter BCP 47 compliance).
    • Fix: Test critical paths after updates and pin versions if stability is critical:
      "require": {
          "php-standard-library/locale": "6.2.0"
      }
      

Debugging Tips

  1. Validation Errors

    • Use Locale::isValid() to debug invalid locales:
      if (!Locale::isValid('en_')) {
          dd('Invalid: missing region'); // Debug output
      }
      
  2. Normalization Issues

    • Compare input vs. output to spot unexpected changes:
      $raw = 'en-us';
      $normalized = Locale::fromString($raw)->toString();
      dd(compact('raw', 'normalized')); // Debug output
      
  3. Performance Bottlenecks

    • Profile locale parsing in high-traffic endpoints:
      $start = microtime(true);
      $locale = Locale::fromString($rawLocale);
      
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
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