In this post, we’re going to make a rule that prevents users from registering with route paths and reserved usernames as their usernames in Laravel.
If you’ve decided to serve your user profiles in a way like this:
/{username}
You may have noticed that it may cause some problems, for example, a user can choose “login” as his/her username and…, Boom!

Not really, if you register your user profiles route after auth routes, it won’t be that bad, but still, you didn’t give your user a chance to have a profile!
“So, what can I do”, you probably asked yourself and maybe google. 🙂
To solve that problem, we’re going to make a rule that prevents users from registering with route paths and reserved usernames as their usernames in Laravel.
Make a rule to exclude Route paths and reserved usernames
First things first, so we need to make a rule:
$ php artisan make:rule AllowedUsername
After that, the code you need to write there is available here and it has comments, so no more cheap talk.
Define your reserved usernames
You need to edit your auth config file here:
config/auth.php
And add your reserved usernames array:
/*
|--------------------------------------------------------------------------
| Reserved Usernames for Registration
|--------------------------------------------------------------------------
|
| Here you may define the usernames that you don't want to be registered.
| Note that routes are already excluded in "AllowedUsername" rule.
|
*/
'reserved_usernames' => [
'admin',
'moderator',
],
It’s also available here as well.
Use the rule
Now, we need to use the rule so it’ll be validated, therefore update your RegisterController here:
app/Http/Controllers/Auth/RegisterController.php
And use the rule namespace at the beginning of your controller:
use App\Rules\AllowedUsername;
And add the rule to the validator:
protected function validator(array $data)
{
...
'username' => [new AllowedUsername, ...],
...
}
Fortify
If you use fortify, you may need to also update your “UpdateUserProfileInformation” action which is located in:
app/Actions/Fortify/UpdateUserProfileInformation.php
And use the rule namespace here as well:
use App\Rules\AllowedUsername;
And update your validation:
public function update($user, array $input)
{
...
'username' => [
new AllowedUsername,
...],
...
}
That’s all! Have fun. 🙂