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

sylius/locale

Locale component for Sylius and PHP apps, providing tools to manage locale codes and formatting. Helps handle available locales, current locale selection, and locale-related utilities for internationalized storefronts and services.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require sylius/locale
    

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

    Sylius\Component\Locale\LocaleServiceProvider::class,
    
  2. Configuration Publish the default config:

    php artisan vendor:publish --provider="Sylius\Component\Locale\LocaleServiceProvider" --tag="config"
    

    Edit config/locale.php to define your supported locales (e.g., ['en_US', 'fr_FR']).

  3. First Use Case Fetch available locales in a controller:

    use Sylius\Component\Locale\LocaleProviderInterface;
    
    class LocaleController extends Controller
    {
        public function __construct(private LocaleProviderInterface $localeProvider) {}
    
        public function index()
        {
            $locales = $this->localeProvider->getLocales();
            return response()->json($locales);
        }
    }
    

Implementation Patterns

Core Workflows

  1. Locale Switching Use the LocaleSwitcher to dynamically change the locale:

    $switcher = app(LocaleSwitcher::class);
    $switcher->switchTo('fr_FR'); // Updates session/cookie
    
  2. Middleware Integration Apply locale switching via middleware (e.g., app/Http/Middleware/SwitchLocale.php):

    public function handle($request, Closure $next)
    {
        $locale = $request->header('Accept-Language') ?? config('app.locale');
        app(LocaleSwitcher::class)->switchTo($locale);
        return $next($request);
    }
    
  3. Formatting Dates/Numbers Leverage the LocaleFormatter for locale-aware formatting:

    $formatter = app(LocaleFormatter::class);
    $formatted = $formatter->formatCurrency(1000, 'en_US'); // "$1,000"
    

Integration Tips

  • Laravel Localization Combine with laravel-localization for route/locale prefixes:

    Route::group(['prefix' => LaravelLocalization::setLocale()], function () {
        // Routes here
    });
    
  • Validation Rules Extend validation with locale-specific rules:

    use Sylius\Component\Locale\Validator\Constraints\Locale;
    
    $validator = Validator::make($data, [
        'locale' => ['required', new Locale(['en_US', 'fr_FR'])]
    ]);
    
  • Database Storage Store locale codes as strings in migrations:

    $table->string('locale')->default(config('app.locale'));
    

Gotchas and Tips

Pitfalls

  1. Locale Code Format Ensure codes match CLDR format (e.g., en_US, not en-US). The package validates this strictly.

  2. Session/Database Sync If using LocaleSwitcher, ensure session driver is configured (e.g., SESSION_DRIVER=file in .env). Cookie-based switching requires SYLIUS_LOCALE_COOKIE config.

  3. Fallback Locale Always define a default_locale in config/locale.php. Missing locales trigger exceptions.

Debugging

  • Missing Locales Check config/locale.php for typos or unsupported codes (e.g., zh_CN is valid, but zh may fail).

  • Formatter Issues Install intl PHP extension for full ICU support:

    sudo apt-get install php-intl  # Linux
    pecl install intl              # Windows
    

Extension Points

  1. Custom Locale Providers Implement LocaleProviderInterface for dynamic locales (e.g., from API):

    class ApiLocaleProvider implements LocaleProviderInterface
    {
        public function getLocales(): array
        {
            return $this->apiClient->fetchLocales();
        }
    }
    
  2. Override Defaults Extend the LocaleServiceProvider in your app’s provider:

    public function register()
    {
        $this->app->extend(LocaleProviderInterface::class, function () {
            return new CustomLocaleProvider();
        });
    }
    
  3. Locale-Specific Logic Use dependency injection to inject LocaleProvider into services:

    class UserService
    {
        public function __construct(private LocaleProviderInterface $localeProvider) {}
    
        public function greet(User $user)
        {
            $locale = $this->localeProvider->getCurrentLocale();
            return match ($locale) {
                'fr_FR' => "Bonjour, {$user->name}",
                default => "Hello, {$user->name}",
            };
        }
    }
    

Performance

  • Caching Locales Cache the LocaleProvider response if locales rarely change:
    $locales = Cache::remember('sylius.locales', 3600, function () {
        return $this->localeProvider->getLocales();
    });
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor