Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Prevent your users to register with your route paths like login, or reserved usernames as their usernames in Laravel. More: https://blog.mahdyar.me/2021/04/18/route-paths-and-reserved-usernames-in-laravel/
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\Route;
class AllowedUsername implements Rule
{
/**
* Create a new rule instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param string $username
* @return bool
*/
public function passes($attribute, $username)
{
$username = trim(strtolower($username));
if ($this->isReservedUsername($username)) {
return false;
}
if ($this->matchesRoute($username)) {
return false;
}
return true;
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'The Username is reserved and cannot be registered.';
}
/**
* Determine whether the given username is in the reserved usernames list.
*
* @param string $username
* @return bool
*/
private function isReservedUsername($username)
{
return in_array($username, config('auth.reserved_usernames'));
}
/**
* Determine whether the given username matches an application route.
*
* @param string $username
* @return bool
*/
private function matchesRoute($username)
{
foreach (Route::getRoutes() as $route) {
if (strtolower($route->uri) === $username) {
return true;
}
}
return false;
}
}
/*
|--------------------------------------------------------------------------
| 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',
],
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment