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

Laravel Tel Input Laravel Package

dotmarn/laravel-tel-input

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require dotmarn/laravel-tel-input
    npm install intl-tel-input --save
    

    Add the package's JS to your layout (e.g., resources/js/app.js):

    import 'intl-tel-input/build/js/intlTelInput';
    import 'laravel-tel-input/dist/js/laravel-tel-input';
    
  2. Publish Assets

    npm run dev  # or `npm run build` for production
    
  3. First Blade Usage

    @telInput(['name' => 'phone', 'defaultCountry' => 'us'])
    

First Use Case

Render a phone input field with auto-formatting and country dropdown:

<form method="POST" action="/contact">
    @telInput(['name' => 'phone', 'required' => true])
    <button type="submit">Submit</button>
</form>

Implementation Patterns

Blade Integration

Basic Workflow

  1. Form Handling

    @telInput([
        'name' => 'user_phone',
        'defaultCountry' => 'auto', // or 'gb', 'us', etc.
        'separateDialCode' => true,
        'onlyCountries' => ['us', 'ca', 'gb']
    ])
    
    • Validation: Use Laravel’s phone rule (e.g., Rule::phone()) with the submitted phone and phone-country fields.
  2. Dynamic Defaults

    @telInput([
        'name' => 'phone',
        'defaultCountry' => $user->country_code ?? 'us'
    ])
    

Livewire Integration

Livewire 2/3

  1. Component Setup
    use Dotmarn\TelInput\Livewire\TelInput;
    
    public function mount() {
        $this->telInput = new TelInput([
            'name' => 'phone',
            'defaultCountry' => 'auto',
        ]);
    }
    
  2. Blade Template
    <livewire:your-component>
        @telInput($telInput)
    </livewire:your-component>
    
  3. Accessing Data
    public function updated($property) {
        $this->validate([
            'phone' => 'required|phone',
            'phone-country' => 'required|string',
        ]);
    }
    

Advanced Patterns

  1. Country Sync

    @telInput([
        'name' => 'phone',
        'syncCountry' => true, // Syncs country dropdown with another field
        'syncCountryField' => 'country_code'
    ])
    
    • Useful for multi-step forms where country is selected first.
  2. Custom Styling Override the default CSS by publishing the package’s assets:

    php artisan vendor:publish --tag=laravel-tel-input-assets
    

    Then extend the published tel-input.css.

  3. Server-Side Logic

    • Normalization: Use libphonenumber (e.g., giggsey/LibPhonenumber-for-PHP) to parse and validate phone numbers:
      use libphonenumber\PhoneNumberUtil;
      use libphonenumber\PhoneNumberFormat;
      
      $phoneUtil = PhoneNumberUtil::getInstance();
      $phone = $phoneUtil->parse($request->phone, $request->{'phone-country'});
      $e164 = $phoneUtil->format($phone, PhoneNumberFormat::E164);
      

Gotchas and Tips

Common Pitfalls

  1. Missing JS Dependencies

    • Error: intlTelInput is not defined.
    • Fix: Ensure intl-tel-input and laravel-tel-input JS are imported after jQuery (required by intl-tel-input).
      // resources/js/app.js
      import $ from 'jquery';
      import 'intl-tel-input/build/js/intlTelInput';
      import 'laravel-tel-input/dist/js/laravel-tel-input';
      
  2. Livewire Data Binding

    • Issue: Country dropdown not updating in Livewire.
    • Fix: Use wire:model alongside @telInput:
      @telInput([
          'name' => 'phone',
          'wire:model' => 'phone'
      ])
      
    • Ensure your Livewire component has:
      public $phone;
      public $phone_country;
      
  3. Validation Mismatches

    • Problem: Submitted phone and phone-country fields don’t match the expected format.
    • Solution: Validate both fields together:
      $this->validate([
          'phone' => 'required|string',
          'phone-country' => 'required|string|in:'.implode(',', ['us', 'ca', 'gb']),
      ]);
      
    • Use giggsey/LibPhonenumber-for-PHP for robust validation:
      $phoneUtil = PhoneNumberUtil::getInstance();
      try {
          $phone = $phoneUtil->parse($request->phone, $request->{'phone-country'});
          $isValid = $phoneUtil->isValidNumber($phone);
      } catch (\Exception $e) {
          $isValid = false;
      }
      

Debugging Tips

  1. Check Console Logs

    • Open browser dev tools (F12) and check for errors like:
      • Uncaught TypeError: intlTelInput is not a function.
      • 404 for missing JS/CSS files (verify npm run dev was executed).
  2. Inspect Hidden Fields

    • The package renders hidden fields for phone-country and phone-number. Verify they exist in the DOM:
      <input type="hidden" name="phone-country" id="phone-country">
      <input type="hidden" name="phone-number" id="phone-number">
      
  3. Country Code Conflicts

    • If defaultCountry is set to an unsupported code (e.g., 'uk' instead of 'gb'), the dropdown may not load correctly. Use ISO 3166-1 alpha-2 codes.

Extension Points

  1. Custom Country Lists

    • Override the default countries by publishing the config:
      php artisan vendor:publish --tag=laravel-tel-input-config
      
    • Modify config/laravel-tel-input.php:
      'countries' => ['us', 'ca', 'mx', 'gb'], // Custom list
      
  2. Dynamic Country Loading

    • Fetch countries via API and pass them to the directive:
      @telInput([
          'name' => 'phone',
          'countries' => $dynamicCountries, // Array of country codes
      ])
      
  3. Localization

    • The package supports localization via intl-tel-input. Add language files to your project and configure:
      // In your JS initialization
      window.intlTelInputGlobals.locales['es'] = {
          // Spanish translations
      };
      
    • Pass the locale to the directive:
      @telInput(['name' => 'phone', 'language' => 'es'])
      
  4. Event Listeners

    • Listen to countrychange or input events via JavaScript:
      document.addEventListener('DOMContentLoaded', function() {
          const input = document.querySelector('#phone');
          input.addEventListener('countrychange', function(e) {
              console.log('Country changed:', e.countryData.iso2);
          });
      });
      
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.
jayeshmepani/jpl-moshier-ephemeris-php
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