Laravel: Allow registration with emails only from a specified(@domain.com) domain

The following are the steps you need to take to only allow registration in your app with emails from specified domains.

ALLOWED_MAIL_DOMAINS= in your .env and config\app.php file

Enter the following into your .env file. This will enable you to add more domains on the fly without having to touch the source code.

...
    ALLOWED_MAIL_DOMAINS=coolorg.com,notsocoolorg.com
...

After that, add the following piece of code in you config\app.php file:

...
    'allowed_mail_domains' => array_merge(
      ['gmail.com'],
      explode(',', env('ALLOWED_MAIL_DOMAINS', ''))
    ),
...

➕ Create a custom rule

From the terminal, run the following command to create a WhitelistedEmail custom rule:

    php artisan make:rule WhitelistedEmail

This will scaffold a new WhitelistedEmail rule class in your app. Navigate to the file and update it with the following piece of code.

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $domain = substr($value, strpos($value, '@') + 1);

        $domains = config('app.allowed_mail_domains');

        return in_array($domain, $domains);
    }

     /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return __('You are not allowed to use this application.');
    }

The next step is to apply the WhitelistedEmail custom rule to the validation array of the email field as in the following:

    use App\Rules\WhitelistedEmail;

    Validator::make($input, [
      ...
      'email' => [
        'required', 
        'string', 
        'email', 
        'max:255', 
        new WhitelistedEmail, 
        'unique:users'
      ],
      ...
    ])->validate();

Now, when you try to register with an email that is not whitelisted, you should see a similar error to the one in the following:

Screenshot 2022-02-28 at 11.30.33.png