Skip to content

Integrations

Validate phone numbers and emails in Laravel

Add a Laravel validation rule that checks emails and phone numbers with the Http facade. Reject undeliverable addresses and invalid numbers, and fail open.

Updated 2026-11-23

This recipe adds two Laravel validation rules, one for emails and one for phone numbers, built on the Http facade. They work in form requests and in Validator::make.

What you need

  • Laravel 10 or later on PHP 8.1 or later.
  • A Qelka API key. A sk_test_ key returns simulated results and never spends credits: see Test mode.
  • The key in .env and read through config. See Authentication.

Steps

1. Configure the key

In .env:

bash
API_KEY=

Paste your key after the equals sign. Keep .env out of version control.

In config/services.php, add inside the returned array:

php
'qelka' => [
    'key' => env('API_KEY'),
    'base_url' => 'https://api.qelka.com/v1',
],

2. A small service

Save as app/Services/Validation.php:

php
<?php

namespace App\Services;

use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class Validation
{
    public static function call(string $path, array $body): ?array
    {
        try {
            $response = Http::withToken(config('services.qelka.key'))
                ->acceptJson()
                ->timeout(10)
                ->connectTimeout(3)
                ->retry(3, 1000, fn ($exception) => $exception instanceof ConnectionException
                    || in_array($exception->response?->status(), [429, 500, 502, 503], true), throw: false)
                ->post(config('services.qelka.base_url') . $path, $body);
        } catch (ConnectionException $exception) {
            Log::warning('validation skipped: unreachable');
            return null;
        }

        if ($response->successful()) {
            return $response->json();
        }

        Log::warning('validation skipped', [
            'type' => $response->json('error.type'),
            'status' => $response->status(),
            'request_id' => $response->header('X-Request-Id'),
        ]);
        return null;
    }
}

retry repeats the call on a connection failure, 429, 500, 502 and 503, one second apart. The result is null when the check could not complete, which the rules below treat as "pass". Every failure is logged with its error type and X-Request-Id. See Errors.

3. The rules

bash
php artisan make:rule DeliverableEmail
php artisan make:rule ValidPhone

app/Rules/DeliverableEmail.php:

php
<?php

namespace App\Rules;

use App\Services\Validation;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;

class DeliverableEmail implements ValidationRule
{
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        $result = Validation::call('/email', ['email' => (string) $value]);
        if ($result === null || $result['status'] !== 'undeliverable') {
            return;
        }
        $fail($result['did_you_mean']
            ? "Did you mean {$result['did_you_mean']}?"
            : 'This email address cannot receive mail.');
    }
}

app/Rules/ValidPhone.php:

php
<?php

namespace App\Rules;

use App\Services\Validation;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;

class ValidPhone implements ValidationRule
{
    public function __construct(private ?string $country = null)
    {
    }

    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        $body = ['phone' => (string) $value];
        if ($this->country) {
            $body['country'] = $this->country;
        }
        $result = Validation::call('/phone', $body);
        if ($result !== null && $result['status'] === 'invalid') {
            $fail('This phone number is not valid.');
        }
    }
}

4. Use them in a form request

php
use App\Rules\DeliverableEmail;
use App\Rules\ValidPhone;

public function rules(): array
{
    return [
        'email' => ['required', 'email', 'unique:users', new DeliverableEmail()],
        'phone' => ['required', new ValidPhone($this->input('country'))],
        'country' => ['required', 'size:2'],
    ];
}

The built-in email and unique rules run first, and the custom rule runs after them. Laravel stops at the first failure only if you add bail, so write 'bail', 'required', 'email', ... to save a paid call on input that is already wrong. To store the normalized number, call Validation::call('/phone', ...) again in your controller and save e164, or cache the first result for the request.

5. Read the result

Result Action
Email undeliverable Fail with did_you_mean
Email risky or unknown Pass. Confirm by email
Phone invalid Fail
Phone unknown Send country, as the form request does
Phone valid Store e164

For IP risk, call Validation::call('/ip', ['ip' => $request->ip()]) and flag the account when risk.level is high. A 422 on private addresses is normal locally.

Handle rate limits

A key is limited to 200 requests per 10 seconds. A 429 carries Retry-After; for form traffic a short retry is enough, and heavy imports belong in a queued job or a bulk job. See Rate limits. Throttle your own signup route so bots cannot spend your credits.

Frequently asked questions

Why a custom rule instead of a controller check?
A rule plugs into form requests and the validator, so errors land in the same error bag as your other fields, translated and displayed the way Laravel already does. You write it once and reuse it on registration, profile and checkout forms, with no change to your controllers.
How do I keep the API key safe in Laravel?
Put it in .env as API_KEY, read it through a config file with config('services.qelka.key'), and never call env() outside config files, since cached config ignores it. Do not expose it to Blade views or JavaScript. Use a test key locally so you never spend credits while developing.
What happens if the API is down?
The rule shown below fails open. On a timeout, a server error or an exhausted balance it passes the value and logs the request id, so registration keeps working. Only a clear negative answer such as an undeliverable email or an invalid phone number fails validation.

Put this check in your product

Get an API key in under a minute. 100 free credits every month, no card required.

  • 100 free credits a month
  • No card
  • Test keys spend nothing
  • Cancel any time