Validating email addresses in Laravel is a fundamental step for maintaining data quality and ensuring reliable communication. We'll explore five implementation methods with code examples, examine the common pitfalls of traditional approaches, and see how Abstract API overcomes them.
How to Implement Email Validation in Laravel
Laravel provides several built-in methods to validate email addresses. Here are four common approaches, from simple syntax checks to more advanced rule configurations for robust data integrity.
Baseline Rule Validation
Laravel includes a default `email` rule. This rule delegates the validation process to the `Egulias\EmailValidator` library, which performs a syntax check against RFC 5322 standards. This is the most basic form of email validation in the framework.
$request->validate([
'email' => ['required', 'string', 'email'],
]);
Parameterized Rule Validation
The standard `email` rule can accept one or more parameters to combine different validation checks. Egulias runs these checks in sequence to confirm the email's format and status. You should only use the flags you need for your specific case.
The available flags provide deeper checks:
- rfc / strict: This flag lets you switch between `RFCValidation` and `NoRFCWarningsValidation` for compliance checks.
- dns: This performs an MX record lookup to confirm the domain can receive mail. It requires the PHP intl extension.
- spoof: This detects potential Unicode homograph attacks in the email address. It also needs the intl extension.
- filter / filter_unicode: This option serves as a fallback to PHP's native `filter_var()` function.
$request->validate([
'email' => 'required|email:strict,dns,spoof',
]);
Fluent Builder Validation
As of Laravel 11.38, the framework exposes a `Rule::email()` method. This method constructs a typed `Email` rule object, which makes the developer's intent more explicit and readable in the code.
This fluent API also allows for conditional logic when you build the rule chain and helps avoid potential string parsing errors. The methods map directly to the parameterized flags, such as `validateMxRecord()` for `dns` and `preventSpoofing()` for `spoof`.
use Illuminate\Validation\Rule;
$request->validate([
'email' => [
'required',
Rule::email()
->rfcCompliant(strict: true)
->validateMxRecord()
->preventSpoofing(),
],
]);
Custom Rule Implementation
For scenarios that require more control, you can create a custom rule class. This approach lets you define your own validation logic by implementation of the `Illuminate\Contracts\Validation\Rule` interface.
The example class `DeliverableEmail` first uses `Egulias\EmailValidator` for a standard RFC check. If the syntax is valid, it extracts the domain from the email address. Then, it uses PHP's `checkdnsrr` function to verify the domain has a valid MX record.
use Egulias\EmailValidator\EmailValidator;
use Egulias\EmailValidator\Validation\RFCValidation;
class DeliverableEmail implements \Illuminate\Contracts\Validation\Rule {
public function passes($attr, $value) {
$v = new EmailValidator;
if (! $v->isValid($value, new RFCValidation)) {
return false;
}
[,$domain] = explode('@', $value, 2);
return checkdnsrr($domain, 'MX');
}
public function message() {
return 'Address is not deliverable.';
}
}
// Usage in a controller or Form Request
$request->validate(['email' => ['required', new DeliverableEmail]]);
Challenges of Email Validation in Laravel
While Laravel's built-in rules offer a convenient starting point, they present several pitfalls that can compromise data accuracy, application performance, and user experience if not properly addressed.
- The baseline
email:rfc
rule permits syntactically valid but undeliverable addresses. It accepts formats with spaces or comments that most mail providers reject, which leads to the storage of useless data. - The
email:dns
flag introduces network latency with a blocking DNS lookup on every request. A bug also accepts domains with A records but no MX records, which creates false positives and performance issues. - Built-in validators like
egulias
and filter_var
lack full Unicode support. They often reject valid international email addresses with non-ASCII characters unless you implement custom punycode conversion logic. - Validation behavior differs between local and production environments. Variations in database collation, PHP builds, or DNS resolvers can cause inconsistent case-sensitivity and DNS check results, which leads to non-reproducible bugs.
Validate Emails with Abstract API
Implement email validation in your Laravel application to improve data integrity and user experience.
Get started for free
How Abstract API Handles Email Validation in Laravel
Traditional Laravel validation methods stop at syntax and DNS checks. Abstract API addresses these core weaknesses by moving the validation logic to a purpose-built service that performs a more complete analysis.
- It runs MX lookups and real-time SMTP handshakes through its own infrastructure, which prevents delays inside your PHP worker.
- It flags free, disposable, role-based, and catch-all domains and proposes corrections for common typos.
- It returns a numeric quality score and a deliverability status, so you can apply business-specific thresholds instead of one-size-fits-all rules.
- It uses a constantly trained machine learning model, which removes the need to maintain blocklists or heuristics in your codebase.
How to Set Up Abstract API in Your Project
Once you know Abstract’s capabilities, you can add its email validation API to your project with a few simple steps.
- Create an Abstract API account, enable the Email Verification service, and copy your API key.
- Add your key to the .env file with the variable ABSTRACT_EMAIL_KEY and then run the php artisan config:cache command.
- Confirm you have an available HTTP client. Laravel 7 and newer include one by default.
- Add a new service configuration to your config/services.php file.
'abstract' => [
'key' => env('ABSTRACT_EMAIL_KEY'),
],
- Create a custom validation rule that calls the API and interprets the response.
- Reference the new rule inside a FormRequest or Validator facade.
Sample Email Validation Implementation
The custom rule below sends the user-submitted email to the Abstract API endpoint. It uses Laravel's built-in HTTP client with a three-second timeout. The rule then checks the JSON response to confirm the email is deliverable, is not from a disposable service, and meets a minimum quality score. If any check fails, the validation returns a custom error message.
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\Http;
class AbstractEmail implements Rule
{
public function passes($attribute, $value)
{
$r = Http::timeout(3)->get(
'https://emailvalidation.abstractapi.com/v1/',
['api_key' => config('services.abstract.key'), 'email' => $value]
)->throw()->json();
return $r['deliverability'] === 'DELIVERABLE'
&& !$r['is_disposable_email']['value']
&& $r['quality_score'] >= 0.8;
}
public function message() { return 'Unable to verify this email address.'; }
}
The API returns a detailed JSON object. The deliverability field provides a clear status like DELIVERABLE or UNDELIVERABLE. The quality_score, a number from 0 to 0.99, lets you tune acceptance thresholds. Granular boolean flags like is_disposable_email and is_role_email offer context for more complex business rules.
{
"email": "johnsmith@gmail.com",
"autocorrect": "",
"deliverability": "DELIVERABLE",
"quality_score": 0.9,
"is_valid_format": { "value": true, "text": "TRUE" },
"is_free_email": { "value": true, "text": "TRUE" },
"is_disposable_email": { "value": false, "text": "FALSE" },
"is_role_email": { "value": false, "text": "FALSE" },
"is_catchall_email": { "value": false, "text": "FALSE" },
"is_mx_found": { "value": true, "text": "TRUE" },
"is_smtp_valid": { "value": true, "text": "TRUE" }
}
Final Thoughts
Traditional Laravel validation only performs surface-level syntax and DNS checks. This approach fails to detect temporary addresses or provide a real measure of deliverability. Abstract API solves these problems with real-time SMTP handshakes and a machine learning model that produces a clear quality score. To reliably validate user emails, consider an account on Abstract API for your free API key.
Validate Emails with Abstract API
Stop fake sign-ups and improve data quality in your Laravel app with proper email validation.
Get started for free