Weave 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

places2be/locales

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require places2be/locales
    

    Add the service provider to config/app.php under providers:

    Wirbelwild\Locales\LocalesServiceProvider::class,
    
  2. Publish Config (Optional)

    php artisan vendor:publish --provider="Wirbelwild\Locales\LocalesServiceProvider" --tag="config"
    

    This generates config/locales.php with default country/language mappings.

  3. First Use Case: Fetching Country/Region Data

    use Wirbelwild\Locales\Facades\Locales;
    
    // Get country name by code
    $countryName = Locales::getCountryName('US'); // "United States"
    
    // Get country code by name
    $countryCode = Locales::getCountryCode('Germany'); // "DE"
    
    // Get all countries as an array
    $countries = Locales::getCountries();
    

Implementation Patterns

Common Workflows

1. Localization & Validation

  • Use Case: Validate country codes in forms or API requests.
use Wirbelwild\Locales\Facades\Locales;

$validCountry = Locales::isValidCountryCode('CA'); // true
$invalidCountry = Locales::isValidCountryCode('XX'); // false
  • Integration with Laravel Validation
use Illuminate\Support\Facades\Validator;

$validator = Validator::make($request->all(), [
    'country_code' => 'required|country_code', // Custom rule
]);

Register a custom rule in AppServiceProvider:

Validator::extend('country_code', function ($attribute, $value, $parameters, $validator) {
    return Locales::isValidCountryCode($value);
});

2. Dynamic Language Handling

  • Use Case: Switch UI language based on user locale.
$languageCode = app()->getLocale(); // e.g., 'fr_FR'
$languageName = Locales::getLanguageName($languageCode); // "French"
$languageCodeFromName = Locales::getLanguageCode('German'); // 'de_DE'
  • Middleware for Locale Detection
namespace App\Http\Middleware;

use Wirbelwild\Locales\Facades\Locales;
use Closure;

class SetLocale
{
    public function handle($request, Closure $next)
    {
        $locale = $request->header('Accept-Language') ?? config('app.locale');
        if (Locales::isValidLanguageCode($locale)) {
            app()->setLocale($locale);
        }
        return $next($request);
    }
}

3. Geographical Data in APIs

  • Use Case: Enrich API responses with country/region details.
$user = User::find(1);
$countryData = Locales::getCountryData($user->country_code);
$response = [
    'user' => $user,
    'country' => $countryData,
];
  • Eager Loading Country Data
$users = User::with(['countryData' => function ($query) {
    $query->select('id', 'country_code')
          ->addSelect(function ($query) {
              return $query->getQuery()->from('countries')
                             ->selectRaw('name as country_name')
                             ->whereColumn('countries.code', 'users.country_code');
          });
}])->get();

4. Custom Data Sources

  • Use Case: Extend or override default data (e.g., for enterprise-specific regions).
// Override country data via config/locales.php
'countries' => [
    'US' => 'United States of America (Custom)',
    'XX' => 'Custom Region', // Add new entries
],
  • Dynamic Data Loading
Locales::setCustomCountries(['XX' => 'Custom Region']);
Locales::setCustomLanguages(['zz' => 'Custom Language']);

Gotchas and Tips

Pitfalls

  1. Case Sensitivity

    • Country/language codes are case-sensitive in the package. Always use uppercase for country codes (e.g., 'US', not 'us').
    • Fix: Normalize input:
      $countryCode = strtoupper($request->input('country_code'));
      
  2. Missing Data for New Regions

    • The package includes standard ISO codes, but custom regions (e.g., "European Union") are not pre-loaded.
    • Workaround: Extend the config or use setCustomCountries() dynamically.
  3. Performance with Large Datasets

    • Loading all countries/languages via Locales::getCountries() or Locales::getLanguages() can be slow if called repeatedly.
    • Optimization: Cache results in AppServiceProvider:
      public function boot()
      {
          Cache::remember('locales.countries', now()->addHours(1), function () {
              return Locales::getCountries();
          });
      }
      
  4. Locale vs. Language Code Confusion

    • getLanguageCode('German') returns 'de_DE' (locale), not just 'de'.
    • Tip: Use getLanguageCode() for full locale or getLanguageCodeShort() (if available) for language-only codes.
  5. Dependency on Published Config

    • The package relies on config/locales.php for customizations. Forgetting to publish the config will default to hardcoded values.
    • Reminder: Always publish the config if extending defaults:
      php artisan vendor:publish --provider="Wirbelwild\Locales\LocalesServiceProvider" --tag="config"
      

Debugging Tips

  1. Validate Inputs Use Locales::isValidCountryCode() or Locales::isValidLanguageCode() to debug invalid inputs:

    if (!Locales::isValidCountryCode($code)) {
        \Log::error("Invalid country code: {$code}");
    }
    
  2. Inspect Data Structure Dump the raw data to understand the package’s internal structure:

    dd(Locales::getCountries());
    dd(Locales::getLanguages());
    
  3. Override Methods for Testing Mock the Locales facade in tests:

    $this->partialMock(Wirbelwild\Locales\Facades\Locales::class, function ($mock) {
        $mock->shouldReceive('getCountryName')
             ->with('US')
             ->andReturn('Mocked USA');
    });
    

Extension Points

  1. Add Custom Regions/Languages Extend the config or use runtime methods:

    // Runtime addition
    Locales::setCustomCountries(['AB' => 'Custom Country']);
    Locales::setCustomLanguages(['ab' => 'Custom Language']);
    
  2. Create Helper Traits Reuse locale logic across projects:

    trait LocaleHelper
    {
        public function getCountryName(string $code): string
        {
            return Locales::getCountryName($code);
        }
    }
    
  3. Integrate with Eloquent Add accessors to models:

    class User extends Model
    {
        public function getCountryNameAttribute()
        {
            return Locales::getCountryName($this->country_code);
        }
    }
    
  4. Localization in Blade Use the facade directly in views:

    <select name="country">
        @foreach(Locales::getCountries() as $code => $name)
            <option value="{{ $code }}">{{ $name }}</option>
        @endforeach
    </select>
    
  5. API Response Formatting Normalize responses with locale data:

    return response()->json([
        'user' => $user,
        'metadata' => [
            'country' => Locales::getCountryData($user->country_code),
            'language' => Locales::getLanguageData(app()->getLocale()),
        ],
    ]);
    
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.
adachsoft/changelog-linter
adachsoft/collection
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel
draftsmaninc/draftsman
square-bit/laravel-volition
himito/laravel-mailman
htinlynn/genius-helper
maco-studios/hephaestus
adachsoft/php-code-style