Validating phone numbers in a Laravel application is vital for data integrity and reliable user communication. We will walk through five methods for this, providing code for each. We will also examine the shortcomings of these traditional approaches and show how Abstract API solves these problems.
How to Implement Phone Number Validation in Laravel
Here are four common methods to validate phone numbers in a Laravel application. Each approach offers a different way to ensure the phone number data you collect is correctly formatted.
Built-in Validator with a Plain E.164 Regex
This method uses Laravel's native validation capabilities combined with a regular expression. The regex pattern checks for numbers that follow the E.164 format, which is an international standard for phone numbers.
The code defines a rule for the "phone" field. The pattern, “^\\+?[1-9]\\d{1,14}$”, requires an optional plus sign at the start, followed by a digit from 1 to 9, and then up to 14 additional digits. This is a simple, dependency-free way to enforce a basic international format.
rules():
return [
'phone' => [
'required',
// + country code, then 1-14 digits (E.164 hard limit is 15)
'regex:/^\\+?[1-9]\\d{1,14}$/'
],
];
Dedicated Rule Object with libphonenumber
A more robust approach is to create a dedicated rule object. You can generate a new rule class with the artisan command “php artisan make:rule ValidPhone”. This class encapsulates the validation logic for a phone number.
Inside the “ValidPhone” class, the “passes” method uses the `libphonenumber` library to parse and validate the number against a specific region, such as “US”. The constructor accepts a region code. If the library successfully parses and validates the number, the method returns true. Otherwise, it returns false.
class ValidPhone implements Rule
{
public function __construct(private string $region = 'US') {}
public function passes($attribute, $value): bool
{
$u = \libphonenumber\PhoneNumberUtil::getInstance();
try {
$p = $u->parse($value, $this->region);
return $u->isValidNumber($p);
} catch (\libphonenumber\NumberParseException) {
return false;
}
}
public function message(): string
{
return 'Invalid phone number for region '.$this->region.'.';
}
}
// Usage:
'phone' => ['required', new ValidPhone('US')];
Global Validator Macro
For application-wide reuse, you can define a global validator macro. This is typically done within the “boot” method of the “AppServiceProvider”. The “Validator::extend” method creates a custom validation rule that you can reference by name throughout your application.
The macro, named “phone_global” in this example, also uses the `libphonenumber` library for validation. It accepts the region code as a parameter directly in the rule definition string. This makes the validation rule easy to read and apply within any FormRequest or validator instance.
// In AppServiceProvider::boot():
Validator::extend('phone_global', function ($attribute, $value, $parameters) {
$region = $parameters[0] ?? null;
$u = \libphonenumber\PhoneNumberUtil::getInstance();
try {
return $u->isValidNumber($u->parse($value, $region));
} catch (\Throwable) {
return false;
}
});
// Then in rules:
'phone' => 'required|phone_global:US';
The Propaganistas/Laravel-Phone Package
You can use a community-developed package like Propaganistas/Laravel-Phone. First, you install it with Composer. This package provides a powerful and flexible phone number validation rule that builds upon `libphonenumber`.
The rule allows you to validate against a single country or a list of countries. It also offers extra features like attribute casting and formatting helpers. The package's full capabilities are available on its GitHub page.
// Install: composer require propaganistas/laravel-phone
// Validation:
'phone' => 'required|phone:US,CA',
// or dynamic: 'phone' => (new \Propaganistas\LaravelPhone\Rules\Phone)->country(['US','CA'])
Challenges of Implementing Phone Number Validation in Laravel
While these methods offer basic checks, they introduce significant reliability and maintenance issues. They often fall short when faced with the complexities of global phone number systems.
- Numbering plans change, and mobile portability breaks prefix-carrier links. Methods that use libphonenumber require constant metadata updates. Without them, the validator flags good numbers or accepts bad ones, which creates inconsistent results.
- The Propaganistas/Laravel-Phone package can be fragile. Minor rule adjustments or composer updates may trigger uncaught errors or ignore modifiers. This can crash a request instead of return a simple validation failure.
- Format validation does not confirm ownership. Disposable or recycled numbers easily pass regex and libphonenumber checks. This allows bot sign-ups, as the methods only check syntax, not if the number is active.
- Model-level casts from packages like Propaganistas/Laravel-Phone create brittle code. They require a specific field assignment order. A wrong order during mass updates throws exceptions before the validator can even run.
Validate Phone Numbers with Abstract API
Implement phone number validation in your Laravel project to collect accurate and reliable user data.
Get started for free
How Abstract API Handles Phone Number Validation in Laravel
Abstract API addresses the core weaknesses of traditional methods by externalizing validation through a real-time, global database.
- It provides real-time correctness through an up-to-date database for over 195 countries, which removes the need for static pattern checks.
- The API response delivers rich context like E.164 format, country metadata, and line type to inform downstream decisions.
- A simple HTTP interface integrates with Laravel’s built-in client through a single GET request, which eliminates the need for C extensions or data updates.
- Predictable error codes connect directly to Laravel’s validation flow to produce user-friendly messages.
How to Bring Abstract API to Your Dev Environment
Once you're familiar with Abstract’s capabilities, the process to add its phone number validation API to your project is simple.
- Sign up at Abstract API, enable the Phone Validation API, and copy your key.
- Add the key to your .env file and reference it in the config/services.php file.
- Confirm Laravel’s HTTP client is available. The laravel/framework dependency, version 7 or higher, already includes Guzzle.
- Create a PhoneValidator class in the app/Services directory to wrap the HTTP GET request.
- Register a custom validation rule or use a Form Request. The request calls the PhoneValidator and checks the "valid" field before it saves.
- Add automated tests that use the Abstract sandbox or mock the responses to maintain a deterministic CI pipeline.
Sample Phone Number Validation Implementation with Abstract API
The code below shows an example of a call inside a Laravel Form Request. It sends the user-provided phone number to the API. If the response indicates the number is not valid, it throws a validation exception with a user-friendly error message.
$response = Http::get('https://phonevalidation.abstractapi.com/v1/', [
'api_key' => config('services.abstract_phone.key'),
'phone' => $this->input('phone'),
]);
if (!$response->json('valid')) {
throw ValidationException::withMessages(['phone' => 'Phone number is not valid.']);
}
A successful request returns a detailed JSON object. The "valid" field confirms the number is assigned and dialable. The "format" object provides both a storage-safe E.164 version and a human-friendly local version. Other fields like "country", "location", "type", and "carrier" allow for geo-based rules, workflows that gate landlines, or flags for high-risk operators.
{
"phone": "14152007986",
"valid": true,
"format": {
"international": "+14152007986",
"local": "(415) 200-7986"
},
"country": {
"code": "US",
"name": "United States",
"prefix": "+1"
},
"location": "California",
"type": "mobile",
"carrier": "T-Mobile USA, Inc."
}
Final Thoughts
Traditional validation with regex patterns or local libraries often fails due to complex international rules and outdated data. This forces teams to maintain complex rule sets. Abstract API solves these issues with a real-time global database and rich contextual data, which ensures accuracy. For reliable phone number validation, create a free account on Abstract API and get your API key.
Validate Phone Numbers with Abstract API
Validate phone numbers in your Laravel project to improve data quality and stop fake users.
Get started for free