Phone Number Formatting, Validation, and Model Casts in Laravel

The Laravel-Phone package makes working with phone numbers in PHP and Laravel a breeze, offering validation rules, attribute casting, utility helpers, and more.

Have you ever built validation around phone numbers that supports multiple countries? This package has helpful validation rules built in, which makes it easy to validate numbers for any country. You can specify acceptible country code formats, but at the same time accept valid "international" numbers:

// Validate either USA or Belguim
Validator::make($request->all(), [
    'phone_number' => 'phone:US,BE',
]);

// Validate US specifically, but also accept other countries
Validator::make($request->all(), [
    'phone_number' => 'phone:US,INTERNATIONAL',
]);

// Use the Phone rule
Validator::make($request->all(), [
    'phone_number' => (new Phone)->country(['US', 'BE']),
]);

// Match country code against another data field
Validator::make($request->all(), [
    'phone_number' => (new Phone)->countryField('custom_country_field'),
    'custom_country_field' => 'required_with:phone_number',
]);

This package uses the PHP port of Google's phone number handling library under the hood, which has robust parsing, formatting, and validation capabilities for working with phone numbers in PHP:

// Formatting examples

$phone = new PhoneNumber('012/34.56.78', 'BE');

$phone->format($format);       // Custom formatting
$phone->formatE164();          // +3212345678
$phone->formatInternational(); // +32 12 34 56 78
$phone->formatRFC3966();       // +32-12-34-56-78
$phone->formatNational();      // 012 34 56 78

You can learn more about this package, get full installation instructions, and view the source code on GitHub. I recommend getting started with the readme for full documentation about this package.


The post Phone Number Formatting, Validation, and Model Casts in Laravel appeared first on Laravel News.

Join the Laravel Newsletter to get all the latest Laravel articles like this directly in your inbox.