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 Setup

  1. Installation

    composer require php-standard-library/locale
    

    Add to composer.json under require if not auto-loaded.

  2. First Use Case: Validating User Locale Input

    use Locale\Locale;
    
    $userLocale = 'en_US'; // From a form or request
    $locale = Locale::fromString($userLocale);
    
    if ($locale->isValid()) {
        // Proceed with normalized locale
        $normalized = $locale->toString(); // 'en_US'
        $language = $locale->getLanguage(); // 'en'
    } else {
        // Fallback to default
        $locale = Locale::fromString('en');
    }
    
  3. Where to Look First

    • Core Class: Locale\Locale (main value object)
    • Validation: Locale::isValid() or Locale::tryFromString()
    • Normalization: toString(), getLanguage(), getRegion()
    • Documentation: Check Locale\Locale PHPDoc for method signatures.

Implementation Patterns

1. Request Handling

Pattern: Sanitize locale input from requests (e.g., API, forms).

use Illuminate\Http\Request;
use Locale\Locale;

public function updateProfile(Request $request)
{
    $locale = $request->input('locale');
    $validatedLocale = Locale::tryFromString($locale) ?? Locale::fromString('en');

    // Store normalized locale in user model
    auth()->user()->update(['locale' => $validatedLocale->toString()]);
}

2. User Model Integration

Pattern: Store and retrieve locales as typed objects.

use Locale\Locale;

class User extends Model
{
    protected $casts = [
        'locale' => Locale::class, // Automatically parses/validates
    ];

    public function getDefaultLocaleAttribute()
    {
        return $this->locale->getLanguage(); // e.g., 'en'
    }
}

3. Translation Service Wrapper

Pattern: Extend Laravel’s trans() helper with locale-aware defaults.

use Illuminate\Support\Facades\App;
use Locale\Locale;

function transWithLocale(string $key, array $replace = [], string|null $locale = null): string
{
    $appLocale = $locale ?? App::getLocale();
    $normalizedLocale = Locale::fromString($appLocale)->toString();

    return trans($key, $replace, [], $normalizedLocale);
}

4. Fallback Logic

Pattern: Chain fallbacks for missing locales.

use Locale\Locale;

function getFallbackLocale(string $preferred): Locale
{
    return Locale::tryFromString($preferred)
        ?? Locale::fromString('en_GB')
        ?? Locale::fromString('en');
}

5. API Response Normalization

Pattern: Ensure consistent locale formatting in responses.

use Locale\Locale;

public function getUserLocales(User $user)
{
    return [
        'primary' => $user->locale->toString(), // 'en_US'
        'language' => $user->locale->getLanguage(), // 'en'
        'region' => $user->locale->getRegion(), // 'US'
    ];
}

Gotchas and Tips

Pitfalls

  1. Case Sensitivity

    • Locale::fromString('EN_US') may fail if the package enforces lowercase.
    • Fix: Normalize input first:
      $locale = Locale::fromString(strtolower($input));
      
  2. Invalid Locale Handling

    • Locale::fromString('invalid') throws an exception by default.
    • Fix: Use tryFromString() for silent fallback:
      $locale = Locale::tryFromString($input) ?? Locale::fromString('en');
      
  3. Region vs. Script Confusion

    • Some locales use scripts (e.g., zh_Hans for Chinese Simplified).
    • Tip: Check getScript() if working with complex locales.
  4. Laravel Cache Key Collisions

    • Caching locale-based data (e.g., cache()->remember('translations_'.$locale, ...)) may clash if locales aren’t normalized.
    • Fix: Always use $locale->toString() as the cache key.

Debugging Tips

  • Validate Locales Early: Add a middleware to validate request locales:

    public function handle(Request $request, Closure $next)
    {
        if ($request->has('locale') && !Locale::tryFromString($request->locale)) {
            abort(422, 'Invalid locale format.');
        }
        return $next($request);
    }
    
  • Log Invalid Locales:

    try {
        $locale = Locale::fromString($input);
    } catch (\InvalidArgumentException $e) {
        \Log::warning("Invalid locale '$input'", ['exception' => $e]);
        $locale = Locale::fromString('en');
    }
    

Extension Points

  1. Custom Validation Rules Extend Laravel’s validation with a custom rule:

    use Illuminate\Validation\Rule;
    use Locale\Locale;
    
    Rule::macro('valid_locale', function ($field, $attribute, $parameters) {
        return Rule::custom(function ($attribute, $value) use ($field) {
            return Locale::tryFromString($value) !== null;
        });
    });
    
    // Usage:
    $request->validate(['locale' => 'valid_locale']);
    
  2. Locale-Specific Logic Use the Locale object to dispatch behavior:

    $locale = Locale::fromString($user->locale);
    if ($locale->getRegion() === 'US') {
        // Apply US-specific formatting
    }
    
  3. Testing Mock locales in tests to avoid flakiness:

    $this->app->singleton(Locale::class, function () {
        return Locale::fromString('test_locale');
    });
    

Performance Notes

  • Avoid Overhead: The package is lightweight, but avoid parsing the same locale repeatedly. Cache results if used in loops.
  • Lazy Loading: Prefer getLanguage()/getRegion() over toString() if you only need parts of the locale.

Config Quirks

  • No Built-in Config: The package is stateless; all behavior is method-based.
  • Default Locale: Set Laravel’s default in config/app.php:
    'locale' => Locale::fromString('en')->toString(),
    
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