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

Libphonenumber For Php Lite Laravel Package

giggsey/libphonenumber-for-php-lite

Lite PHP port of Google’s libphonenumber: parse, validate, format, and store international phone numbers. Includes core PhoneNumberUtils only (no geolocation/carrier/short number info). Requires PHP 8.1+ and mbstring; install via Composer.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require giggsey/libphonenumber-for-php-lite
    

    Ensure mbstring extension is enabled in your PHP environment.

  2. First Use Case: Parse and validate a phone number:

    use libphonenumber\PhoneNumberUtil;
    
    $phoneUtil = PhoneNumberUtil::getInstance();
    $number = $phoneUtil->parse('+14155552671', 'US');
    $isValid = $phoneUtil->isValidNumber($number); // true
    
  3. Where to Look First:


Implementation Patterns

Core Workflows

  1. Parsing and Validation:

    $phoneUtil = PhoneNumberUtil::getInstance();
    $number = $phoneUtil->parse($rawInput, $regionCode); // e.g., '1234567890', 'US'
    $isValid = $phoneUtil->isValidNumber($number);
    
  2. Formatting:

    // E164: "+14155552671"
    $e164 = $phoneUtil->format($number, PhoneNumberFormat::E164);
    
    // National: "(415) 555-2671"
    $national = $phoneUtil->format($number, PhoneNumberFormat::NATIONAL);
    
    // International: "+1 415-555-2671"
    $international = $phoneUtil->format($number, PhoneNumberFormat::INTERNATIONAL);
    
  3. Geographic Formatting:

    // Format for dialing from another country (e.g., UK)
    $ukDialFormat = $phoneUtil->formatOutOfCountryCallingNumber($number, 'GB');
    
  4. Number Type Detection:

    $numberType = $phoneUtil->getNumberType($number); // e.g., PhoneNumberType::MOBILE
    
  5. Number Comparison:

    $isMatch = $phoneUtil->isNumberMatch($number1, $number2); // Returns confidence level
    

Integration Tips

  • Laravel Request Validation: Use the package in Form Requests or API validations:

    use libphonenumber\PhoneNumberUtil;
    
    public function rules()
    {
        return [
            'phone' => ['required', function ($attribute, $value, $fail) {
                $phoneUtil = PhoneNumberUtil::getInstance();
                try {
                    $number = $phoneUtil->parse($value);
                    if (!$phoneUtil->isValidNumber($number)) {
                        $fail('The phone number is invalid.');
                    }
                } catch (\libphonenumber\NumberParseException $e) {
                    $fail('The phone number is invalid.');
                }
            }],
        ];
    }
    
  • Database Storage: Store normalized E164 format to avoid inconsistencies:

    $e164 = $phoneUtil->format($number, PhoneNumberFormat::E164);
    $user->phone = $e164;
    
  • User Input Handling: Use parse() without a region code for flexible parsing:

    $number = $phoneUtil->parse($userInput); // Auto-detects region if possible
    
  • Caching: Cache the PhoneNumberUtil instance for performance:

    $phoneUtil = Cache::remember('phoneUtil', now()->addDays(30), function () {
        return PhoneNumberUtil::getInstance();
    });
    

Gotchas and Tips

Pitfalls

  1. Region Code Ambiguity:

    • Parsing without a region code (e.g., parse('12345')) may return unexpected results. Always specify a region if possible.
    • Example: '12345' could be valid in some countries but invalid in others.
  2. Invalid Input Handling:

    • Always wrap parse() in a try-catch block to handle NumberParseException:
      try {
          $number = $phoneUtil->parse($invalidInput);
      } catch (\libphonenumber\NumberParseException $e) {
          // Handle invalid input (e.g., log or return user-friendly error)
      }
      
  3. Metadata Updates:

    • The library relies on Google's metadata. If you encounter issues with specific numbers, check if the metadata is outdated (e.g., new area codes or number types).
    • Verify against Google's Online Demo if results seem incorrect.
  4. Performance:

    • Parsing and formatting are lightweight, but avoid parsing the same number repeatedly in loops. Cache results if needed.
  5. Short Numbers:

    • This lite version does not support short numbers (e.g., toll-free, premium-rate). Use the full libphonenumber-for-php package for those features.

Debugging Tips

  1. Inspect Parsed Numbers: Use var_dump() or json_encode() to debug PhoneNumber objects:

    $number = $phoneUtil->parse('+442071838750', 'GB');
    echo json_encode($number, JSON_PRETTY_PRINT);
    
  2. Check Region Codes: Use getSupportedRegions() to list valid region codes:

    $regions = $phoneUtil->getSupportedRegions();
    
  3. Example Numbers: Generate valid examples for testing:

    $example = $phoneUtil->getExampleNumber('US'); // e.g., "+16502530000"
    $mobileExample = $phoneUtil->getExampleNumberByType('US', PhoneNumberType::MOBILE);
    

Extension Points

  1. Custom Validation Logic: Extend validation by combining with Laravel's validation rules:

    $validator = Validator::make($data, [
        'phone' => ['required', 'phone:US'], // Custom rule for US numbers
    ]);
    
  2. Service Provider: Bind the PhoneNumberUtil instance in Laravel's service container for dependency injection:

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton(\libphonenumber\PhoneNumberUtil::class, function () {
            return \libphonenumber\PhoneNumberUtil::getInstance();
        });
    }
    
  3. Testing: Use the package in PHPUnit tests to validate phone numbers:

    public function testValidPhoneNumber()
    {
        $phoneUtil = PhoneNumberUtil::getInstance();
        $number = $phoneUtil->parse('+14155552671', 'US');
        $this->assertTrue($phoneUtil->isValidNumber($number));
    }
    
  4. Localization: Format numbers according to user preferences (e.g., store preferred format in the database):

    $format = $user->preferredPhoneFormat ?? PhoneNumberFormat::NATIONAL;
    $formatted = $phoneUtil->format($number, $format);
    

Config Quirks

  • Time Zone Handling: The library does not handle time zones. If you need to associate phone numbers with time zones (e.g., for SMS delivery), implement this logic separately.

  • Legacy Data: If migrating from an older version (e.g., v8), ensure serialized data is compatible. The package includes fixes for backward compatibility (e.g., unserialize() support).

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.
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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