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.
Installation
composer require php-standard-library/locale
No additional configuration is required—use the Locale class directly.
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".');
}
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.Where to Look Next
Locale.php to understand parsing logic or extend behavior.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);
}
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).');
}
}],
];
}
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();
}
}
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);
}],
]);
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);
Service Providers
Bind the Locale class to the container for dependency injection:
$app->bind(Locale::class, function () {
return Locale::fromString(config('app.locale'));
});
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']);
});
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();
}
$locale = cache()->remember("locale.{$rawLocale}", now()->addHours(1), function () use ($rawLocale) {
return Locale::fromString($rawLocale);
});
$locales = ['en_US', 'fr_FR', 'invalid'];
$validLocales = array_filter($locales, fn($l) => Locale::isValid($l));
// Example: Normalize 'en-US' to 'en_US' before API call
const normalizedLocale = locale.replace(/-/g, '_');
await axios.post('/api/profile', { locale: normalizedLocale });
Case Sensitivity
Locale::fromString('EN_US') may fail if the package enforces lowercase language codes (e.g., en_US).$locale = Locale::fromString(strtolower($rawLocale));
Private-Use and Extension Tags
sr-Latn-RS (Serbian Latin script) or und (undetermined) may not be handled by default.try {
$locale = Locale::fromString('sr-Latn-RS');
} catch (InvalidArgumentException $e) {
$locale = Locale::fromString('sr'); // Fallback
}
Database Storage
Locale objects directly in databases may fail if the column type is string but the object isn’t cast properly.protected $casts = [
'locale' => 'string', // Store as string, validate on set
];
Locale Fallbacks
en_US → en) may not match Laravel’s default fallback chain.$locale = Locale::fromString($userLocale);
if (!$locale->isValid()) {
$locale = Locale::fromString(config('app.fallback_locale'));
}
Package Updates
"require": {
"php-standard-library/locale": "6.2.0"
}
Validation Errors
Locale::isValid() to debug invalid locales:
if (!Locale::isValid('en_')) {
dd('Invalid: missing region'); // Debug output
}
Normalization Issues
$raw = 'en-us';
$normalized = Locale::fromString($raw)->toString();
dd(compact('raw', 'normalized')); // Debug output
Performance Bottlenecks
$start = microtime(true);
$locale = Locale::fromString($rawLocale);
How can I help you explore Laravel packages today?