Go back to the homepage

How to limit registrations by domain in Laravel

Sometimes it makes sense to only allow users with a certain domain to register with your application, in the post we discuss how to accomplish this.

There are many use cases where it makes sense to lock registration for your web app to only certain domains, for example an internal tool for users of your company.

✅ Create a new Validation Rule

php artisan make:rule IsAllowedDomain

This will create a new custom validation rule that you can use anywhere you use request validation.

✅ Create an array of allowed domains

Open the generated class and add a protected array of domains you want to allow

/**
 * Allowed email domains for user registration
 *
 * @var array
 */
protected $allowedDomains = [
   'domain.com',
   'another-domain.com',
];

✅ Update your passes method

We need to check if the value being validated is in our array of allowed domains

public function passes($attribute, $value)
{
   $domain = substr(strrchr($value, "@"), 1);
   
   if (in_array($domain, $this->allowedDomains)) {
      return true;
   }
   
   return false;
}

✅ Update your message method

This is the error message you will show if the validation fails.

public function message()
{
    return 'We appreciate your interest in joining, however 
    at the moment we only offer this service to those 
    with **your domains*** email addresses.';
}

✅ Update the validator method of your registration controller

  • Import your new rule
use App\Rules\IsAllowedDomain;
  • Add a new validation rule to your email field validation rule set
'email' => [
    'required',
    'string', 
    'email',
    'max:255',
    'unique:users,email',
    new IsAllowedDomain
],

✅ Done!

You might consider adding a note on the registration form to alert potential users to use a valid domain.