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

Country And Phone Number Laravel Package

apie/country-and-phone-number

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require apie/country-and-phone-number
    

    Verify the package loads by running:

    php artisan package:discover
    
  2. First Use Case: Validate and Parse a Phone Number

    use Apie\CountryAndPhoneNumber\PhoneNumber;
    
    $phoneNumber = new PhoneNumber('+14155552671'); // Google's US HQ
    $isValid = $phoneNumber->isValid(); // true
    $countryCode = $phoneNumber->getCountryCode(); // 'US'
    
  3. First Use Case: Fetch Country Data

    use Apie\CountryAndPhoneNumber\Country;
    
    $country = Country::getByCode('DE');
    $countryName = $country->getName(); // 'Germany'
    $dialCode = $country->getDialCode(); // '+49'
    
  4. Where to Look First

    • Namespace: Apie\CountryAndPhoneNumber
    • Classes: PhoneNumber, Country, CountryCollection
    • Monorepo Docs: Apie Monorepo (for deeper integration).

Implementation Patterns

Core Workflows

1. Phone Number Validation and Formatting

  • Input Sanitization:
    $phone = new PhoneNumber('+44 20 7946 0958');
    $phone->normalize(); // '+442079460958'
    
  • Country-Specific Validation:
    $phone = new PhoneNumber('0123456789');
    $phone->setCountryCode('IN'); // India
    $phone->isValid(); // true/false
    

2. Country Data Retrieval

  • Filter Countries:
    use Apie\CountryAndPhoneNumber\CountryCollection;
    
    $countries = CountryCollection::all()
        ->filterByDialCode('+1'); // US/Canada
    
  • Lazy Loading:
    $country = Country::getByName('France'); // Loads on demand
    

3. Integration with Laravel Requests

  • Form Request Validation:
    use Illuminate\Validation\Rule;
    
    $rules = [
        'phone' => ['required', function ($attribute, $value, $fail) {
            $phone = new PhoneNumber($value);
            if (!$phone->isValid()) {
                $fail('Invalid phone number.');
            }
        }],
    ];
    
  • Request Macro:
    use Apie\CountryAndPhoneNumber\PhoneNumber;
    
    Request::macro('parsePhone', function () {
        return new PhoneNumber($this->phone);
    });
    

4. Localization

  • Translate Country Names:
    $country = Country::getByCode('JP');
    $name = __($country->getName()); // Use Laravel's translation
    

Advanced Patterns

1. Caching Country Data

  • Cache country collection for performance:
    $countries = Cache::remember('apie.countries', now()->addDays(7), function () {
        return CountryCollection::all();
    });
    

2. Custom Phone Number Rules

  • Extend validation logic:
    class CustomPhoneRule extends \Illuminate\Validation\Rules\In {
        public function validateStringAttribute($attribute, $value, $fail) {
            $phone = new PhoneNumber($value);
            if (!$phone->isValid() || !$phone->getCountryCode() === 'US') {
                $fail('Must be a valid US number.');
            }
        }
    }
    

3. API Response Formatting

  • Normalize phone numbers in API responses:
    $user = User::find(1);
    $user->phone = (new PhoneNumber($user->phone))->normalize();
    return response()->json($user);
    

Gotchas and Tips

Pitfalls

  1. No Official Documentation

    • Rely on method names (PSR-12 compliant) and type hints. Example:
      $phone->getCountryCode() // Returns string, not Country object.
      
  2. Monorepo Maintenance

    • Issues/PRs must be submitted to the Apie Monorepo, not this package’s repo.
  3. Edge Cases in Validation

    • Some numbers may pass isValid() but lack a country code (e.g., short codes). Always check:
      if ($phone->isValid() && $phone->getCountryCode()) {
          // Safe to use
      }
      
  4. Performance with Large Datasets

    • CountryCollection::all() loads all countries (~250) into memory. Cache aggressively if used frequently.

Debugging Tips

  1. Inspect Phone Number Components

    $phone = new PhoneNumber('+447900123456');
    dd([
        'raw' => $phone->getRawNumber(),
        'national' => $phone->getNationalNumber(),
        'country' => $phone->getCountryCode(),
    ]);
    
  2. Check Country Data

    $country = Country::getByCode('XK'); // Kosovo (disputed)
    dd($country->toArray()); // Inspect all available fields
    
  3. Enable Strict Typing

    • Add to composer.json to catch type mismatches early:
      "config": {
          "platform-check": true
      }
      

Extension Points

  1. Add Custom Country Data

    • Extend the Country class or use a decorator pattern:
      class ExtendedCountry extends Country {
          public function getRegion() {
              return $this->getSubregion(); // Custom logic
          }
      }
      
  2. Override Validation Logic

    • Create a wrapper for PhoneNumber:
      class BusinessPhoneNumber extends PhoneNumber {
          public function isValid() {
              $isValid = parent::isValid();
              return $isValid && $this->startsWith('+1'); // US-only
          }
      }
      
  3. Integrate with Laravel Scout

    • Index country/phone data for search:
      use Laravel\Scout\Searchable;
      
      class Country extends \Apie\CountryAndPhoneNumber\Country implements Searchable {
          public function toSearchableArray() {
              return [
                  'name' => $this->getName(),
                  'code' => $this->getCode(),
              ];
          }
      }
      

Config Quirks

  • No Configuration File: The package is stateless. All behavior is driven by method calls.
  • Locale Support: Country names are returned in English by default. Use Laravel’s __() for translations:
    $countryName = __($country->getName());
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui