laravel-phone

repository·master·Indexed 25 days ago

https://github.com/propaganistas/laravel-phone

A Laravel package providing robust phone number functionality via a PHP port of Google's libphonenumber. It includes validation rules with country whitelisting and type constraints, Eloquent attribute casting (RawPhoneNumberCast and E164PhoneNumberCast), and a PhoneNumber utility class for formatting (E.164, International, RFC3966, National) and analyzing phone numbers.

Tokens
4.8K
Snippets
9
Records
28
Agent score
83%

What's inside laravel-phone

  1. Upgrade from 4.x to 5.x: Utility PhoneNumber class

    master

    Several methods have been removed or changed in the PhoneNumber class:

    • make() removed: Use the phone() helper or the new PhoneNumber() constructor instead.
    • ofCountry() removed: The country must now be specified during object construction.
    • numberLooksInternational() removed: This undocumented method is no longer available.
    // Instead of PhoneNumber::make($number, $country)
    phone($number, $country)
    // or
    new PhoneNumber($number, $country)
    
    // Instead of $object->ofCountry($country)
    $object = new PhoneNumber($number, $country);
  2. Validate phone numbers

    master

    You can validate phone numbers using the phone keyword in validation rules or the Propaganistas\LaravelPhone\Rules\Phone class.

    Key features:

    • Country Whitelisting: Specify ISO 3166-1 alpha-2 codes (e.g., phone:US,BE).
    • Dynamic Country Matching: Match against another field by appending _country to the phone field name (e.g., my_input and my_input_country) or by providing the field name as a parameter (phone:custom_country_field).
    • International Support: Use INTERNATIONAL to allow any valid internationally formatted number alongside whitelisted countries (e.g., phone:INTERNATIONAL,BE).
    • Type Constraints: Restrict to specific types like mobile or fixed_line (e.g., phone:mobile).
    • Blacklisting Types: Prepend an exclamation mark to exclude a type (e.g., phone:!mobile).
    • Lenient Validation: Use LENIENT to check only the length of the number instead of carrier patterns (e.g., phone:LENIENT).
  3. Implement searchable phone number variants

    master

    To support complex searches across different phone number formats, you can store multiple searchable variants in your database. This approach involves using an observer (like a Laravel saving() observer) to pre-calculate and populate these columns before the record is saved.

    Recommended Database Columns:

    • phone_normalized: Raw input with all non-numeric characters stripped.
    • phone_national: National formatted number with all non-numeric characters stripped.
    • phone_e164: The E.164 formatted version of the number.

    Implementation Example: Use a model observer to update these fields whenever the phone field changes.

    public function saving(User $user)
    {
        if ($user->isDirty('phone') && $user->phone) {
            $user->phone_normalized = preg_replace('/[^0-9]/', '', $user->phone);
            $user->phone_national = preg_replace('/[^0-9]/', '', phone($user->phone, $user->phone_country)->formatNational());
            $user->phone_e164 = phone($user->phone, $user->phone_country)->formatE164();
        }
    }
  4. Preserve raw user input for display

    master

    If you need to present the phone number back to the user exactly as they typed it (for UX purposes), you must store both the raw input and the associated country code, as formatting the number to a standard like E.164 will lose the original formatting.

    Requirements:

    • A column for the raw input (e.g., phone of type varchar).
    • A column for the correlated country code (e.g., phone_country of type varchar).
  5. Install Laravel Phone

    master

    Install the latest version of the package using Composer. The Service Provider is automatically discovered by Laravel. You should also add a custom translation for the phone validation rule in your lang/validation.php files.

    composer require propaganistas/laravel-phone
    // lang/validation.php
    'phone' => 'The :attribute field must be a valid number.',
  6. Implement unique phone number storage using E.164

    master

    To ensure phone numbers are globally unique and easily identifiable, store them in the E.164 format. This format inherently includes the country code and can be generated using the phone() helper.

    Requirements:

    • A single database column (e.g., phone of type varchar) to store the formatted number.
    • Logic to format the user input to E.164 before persisting it to the database.
  7. Upgrade from 5.x to 6.x: Service Container

    master

    The libphonenumber singleton registration has been removed from the service container. If your application relies on resolving libphonenumber from the container, you must manually register it in a Service Provider.

    $this->app->singleton('libphonenumber', function ($app) {
        return PhoneNumberUtil::getInstance();
    });
  8. Upgrade from 5.x to 6.x: Validation Rules

    master

    When upgrading to version 6.x, update your validation rules to account for libphonenumber shifting from class constants to native enums.

    String-based validation rules

    If you used constants in strings, append ->value or use the string name directly.

    Object-based validation rules

    If you passed integer values to object-based rules, you must now convert them to the appropriate enum using libphonenumber\PhoneNumberType::from($value).

    Rename of fixed line shortcut

    The shortcut method for fixed line numbers has been renamed to snake case.

    // String-based validation
    'phonefield' => 'phone:'.libphonenumber\PhoneNumberType::MOBILE->value,
    'phonefield' => 'phone:mobile',
    
    // Object-based validation
    'phonefield' => (new Phone)->type(libphonenumber\PhoneNumberType::from(1)),
    'phonefield' => (new Phone)->type(libphonenumber\PhoneNumberType::MOBILE),
    
    // Fixed line shortcut rename
    (new Phone)->fixed_line();
  9. Upgrade from 4.x to 5.x: Validation

    master

    Upgrading to 5.x requires updates to validation rule names and introduces new rule object support.

    • New Feature: You can now use the Phone rule as a rule object: (new Phone)->mobile()->country('BE').
    • Rename detect(): The detect() method on the Rule macro is now international().
    • Rename AUTO: The AUTO parameter is now INTERNATIONAL.
  10. Upgrade from <5.3 to >=5.3

    master
    The internal dependency has changed from giggsey/libphonenumber-for-php to giggsey/libphonenumber-for-php-lite. This is a non-breaking change for standard Laravel-Phone functionality. However, if you have defined custom macros that require geolocation, carrier information, or short number info, you must explicitly require giggsey/libphonenumber-for-php in your project.
  11. Upgrade from 4.x to 5.x: Attribute Casting

    master
    In version 5.x, RawPhoneNumberCast will throw an exception if it is invoked with an invalid phone object (e.g., when accessing the casted attribute). Ensure you validate phone numbers before persisting them and provide the appropriate country code to the cast.
  12. Upgrade from 5.x to 6.x: Utility PhoneNumber class

    master

    Version 6.x introduces several breaking changes to the PhoneNumber utility class:

    • Exception Handling: Custom package exceptions (e.g., NumberParseException, CountryCodeException) have been removed. The package now bubbles libphonenumber exceptions directly (typically libphonenumber\NumberParseException).
    • Constructor Signature: PhoneNumber::__construct() no longer accepts null for the $number parameter.
    • getType(): Now returns a libphonenumber\PhoneNumberType enum instead of a string.
    • isOfType($type): Now accepts a string or libphonenumber\PhoneNumberType enum. If passing a string that cannot be converted, it throws an InvalidArgumentException.
    • format($format): Now accepts a string or libphonenumber\PhoneNumberFormat enum. If passing a string that cannot be converted, it throws an InvalidArgumentException.