Phone Number Formatting, Validation, and Model Casts in Laravel - TechvBlogs

Phone Number Formatting, Validation, and Model Casts in Laravel

In this article, You will learn How to Format, Validate and Casts Model in Laravel.


Smit Pipaliya - Author - TechvBlogs
Smit Pipaliya
 

4 weeks ago

TechvBlogs - Google News

In the realm of PHP and Laravel, managing phone numbers seamlessly becomes a reality with the Laravel-Phone package. This powerful toolkit simplifies the process by offering comprehensive validation rules, attribute casting, utility helpers, and more.

Streamlined Validation for Multiple Countries

Have you ever faced the challenge of implementing phone number validation that caters to diverse countries? The Laravel-Phone package comes to the rescue with built-in validation rules that effortlessly handle numbers from any corner of the globe. Tailor your validation by specifying acceptable country code formats while ensuring compatibility with valid "international" numbers.

Example 1: Validate Either USA or Belgium

Validator::make($request->all(), [
    'phone_number' => 'phone:US,BE',
]);

Example 2: Validate US Specifically, but Also Accept Other Countries

Validator::make($request->all(), [
    'phone_number' => 'phone:US,INTERNATIONAL',
]);

Example 3: Utilize the Phone Rule

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

Example 4: 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',
]);

Harnessing Google's Phone Number Handling Library

Under the hood, Laravel-Phone leverages the PHP port of Google's phone number handling library. This ensures robust parsing, formatting, and validation capabilities, elevating your phone number manipulation game 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

Dive Deeper into Laravel-Phone

Explore more about Laravel-Phone, delve into comprehensive installation instructions, and examine the source code on GitHub. For a solid foundation, kickstart your journey with the readme for in-depth documentation on this indispensable package. Elevate your phone number validation game with Laravel-Phone and ensure a seamless experience for users across the globe.

Comments (0)

Comment


Note: All Input Fields are required.