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

Intl Laravel Package

symfony/intl

Symfony Intl component provides access to ICU localization data in PHP: locales, languages, scripts, regions, currencies, and more. Includes tooling to compress bundled data (with zlib) for smaller installs and faster lookups.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require symfony/intl
    

    Ensure your PHP environment has the ICU extension (php-intl) installed and enabled.

  2. First Use Case: Localize a string with pluralization (e.g., for translations):

    use Symfony\Component\Intl\Intl;
    
    $count = 5;
    $message = Intl::select(
        'The user has {0, plural, one {# message} other {# messages}}.',
        $count,
        ['#' => $count]
    );
    // Output: "The user has 5 messages."
    
  3. Where to Look First:

    • Official Documentation (covers core features like formatting, localization, and ICU data).
    • Symfony\Component\Intl\Intl (main class for static utility methods).
    • Symfony\Component\Intl\Locale (for locale-specific operations).

Implementation Patterns

Common Workflows

  1. Locale Handling:

    • Detect user locale dynamically (e.g., from request headers or session):
      use Symfony\Component\Intl\Locale;
      
      $locale = Locale::getDefault(); // e.g., 'en_US'
      $locale = Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']); // Parse Accept-Language header
      
    • Validate locales:
      if (Locale::hasLocale($locale)) {
          // Proceed with localization
      }
      
  2. Number/Date Formatting:

    • Format numbers with locale-specific rules:
      $formatter = new \NumberFormatter($locale, \NumberFormatter::DECIMAL);
      echo $formatter->format(1234.56); // e.g., "1,234.56" (en_US) or "1.234,56" (de_DE)
      
    • Parse and format dates:
      $date = new \DateTime('2023-12-25');
      $formatter = new \IntlDateFormatter(
          $locale,
          \IntlDateFormatter::LONG,
          \IntlDateFormatter::LONG
      );
      echo $formatter->format($date); // e.g., "December 25, 2023" (en_US)
      
  3. Pluralization and Gender Rules:

    • Use ICU message syntax for complex rules:
      $gender = 'male';
      $message = Intl::select(
          '{gender, select,
              male {Hello, Sir!}
              female {Hello, Ma’am!}
              other {Hello, Guest!}
          }',
          ['gender' => $gender]
      );
      
  4. Collation (Sorting):

    • Sort strings according to locale rules:
      $collator = new \Collator($locale);
      $collator->sort($strings); // Array of strings sorted by locale
      
  5. Integration with Laravel:

    • Service Provider: Bind Intl utilities to the container:
      // app/Providers/AppServiceProvider.php
      public function register()
      {
          $this->app->singleton(\Symfony\Component\Intl\Intl::class);
      }
      
    • Middleware: Set locale from request:
      // app/Http/Middleware/SetLocale.php
      public function handle($request, Closure $next)
      {
          $locale = Locale::acceptFromHttp($request->header('Accept-Language'));
          app()->setLocale($locale);
          return $next($request);
      }
      

Gotchas and Tips

Pitfalls

  1. ICU Extension Dependency:

    • The package relies on PHP’s php-intl extension. Verify it’s enabled:
      php -m | grep intl
      
    • If missing, install via:
      pecl install intl
      
      or use a system package manager (e.g., apt-get install php-intl on Ubuntu).
  2. Locale Data Compression:

    • The package ships with uncompressed ICU data (~10MB). Compress it to reduce memory usage:
      php vendor/symfony/intl/Resources/bin/compress
      
    • Warning: Compression is irreversible. Only run this if you’re sure you won’t need to update the data later.
  3. Performance with Large Datasets:

    • Avoid instantiating formatters/collators in loops. Reuse instances:
      $formatter = new \NumberFormatter($locale); // Reuse this
      foreach ($numbers as $number) {
          echo $formatter->format($number);
      }
      
  4. Edge Cases in Pluralization:

    • ICU’s pluralization rules can be complex (e.g., Arabic, Russian). Test thoroughly with:
      $count = 11; // Edge case for some locales
      $message = Intl::select('{0, plural, one {#} other {#}}', $count);
      
  5. Time Zone Handling:

    • IntlDateFormatter uses the system’s default time zone. Explicitly set it if needed:
      $formatter = new \IntlDateFormatter(
          $locale,
          \IntlDateFormatter::LONG,
          \IntlDateFormatter::LONG,
          'America/New_York',
          \DateTimeZone::PERIOD1,
          'en_US'
      );
      

Debugging Tips

  1. Validate Locales:

    • Use Locale::getDisplayName() to debug locale names:
      echo Locale::getDisplayName('en_US', 'en_US'); // "English (United States)"
      
    • Check if a locale is valid:
      if (!Locale::hasLocale('invalid_locale')) {
          throw new \InvalidArgumentException('Invalid locale');
      }
      
  2. Log ICU Errors:

    • Wrap Intl operations in try-catch to log ICU-specific errors:
      try {
          $formatter->format($date);
      } catch (\IntlException $e) {
          Log::error('ICU Error: ' . $e->getMessage());
      }
      
  3. Fallback Locales:

    • Provide fallbacks for unsupported locales:
      $locales = ['en_US', 'en', 'en_GB']; // Fallback chain
      $locale = Locale::acceptFromHttp($request->header('Accept-Language'), $locales);
      

Extension Points

  1. Custom ICU Data:

    • Override the default ICU data by replacing the Resources/stubs directory with your own compiled data.
  2. Event Listeners for Locale Changes:

    • Listen for locale changes in Laravel (e.g., after user login):
      // app/Providers/EventServiceProvider.php
      public function boot()
      {
          event(new \Illuminate\Auth\Events\LoggedIn($user));
      }
      
      Then handle it in a listener to update the locale.
  3. Hybrid Formatting:

    • Combine Intl with Laravel’s built-in localization (e.g., for pluralization in Blade templates):
      // app/Helpers/IntlHelper.php
      function pluralize($count, $singular, $plural)
      {
          return Intl::select(
              '{0, plural, one {' . $singular . '} other {' . $plural . '}}',
              $count
          );
      }
      
      Use in Blade:
      {{ pluralize($count, 'Item', 'Items') }}
      
  4. Testing:

    • Mock Intl for unit tests:
      $this->partialMock(Intl::class, ['select'])
          ->expects('select')
          ->with('...', $count)
          ->willReturn('Mocked result');
      
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.
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
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope