Validate Allowed Email Domains in Laravel


June 25th, 2021

Validate Allowed Email Domains in Laravel

The Email Domain Rule package for Laravel can define a subset of allowed email domains you can use within a validator. The email domains are stored in the database, and the accompanying validation rule uses the database to verify an email field:

1use HFarm\EmailDomainRule\EmailDomainRule;
2use Illuminate\Support\Facades\Validator;
4$email = '';
7 'email' => $email,
8], [
9 'email' => [
10 'string',
11 'email',
12 new EmailDomainRule,
13 ],

This package also has wildcard support, which can come in handy in a multi-tenant application where you’d like to constraint which domain(s) a user can register within a given tenant. The package readme illustrates model customizations you can use to make this package support validation for multiple tenants:

1use HFarm\EmailDomainRule\EmailDomainRule as BaseEmailDomain;
2use Illuminate\Database\Eloquent\Builder;
4class EmailDomain extends BaseEmailDomain
6 protected $fillable = [
7 'domain',
8 'tenant_id',
9 ];
11 protected static function booted()
12 {
13 static::addGlobalScope('tenantAware', function (Builder $builder) {
14 $builder->where('tenant_id', auth()->user()->tenant_id);
15 });
16 }

You can learn more about this package, get full installation instructions, and view the source code on GitHub.

This package was submitted to our Laravel News Links section. Links is a place the community can post packages and tutorials around the Laravel ecosystem. Follow along on Twitter @LaravelLinks

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.