-
Notifications
You must be signed in to change notification settings - Fork 9
Getting Started
This package can be installed via Composer
composer require taylornetwork/laravel-username-generator
To publish the Config to config/username_generator.php
php artisan vendor:publish --provider="TaylorNetwork\UsernameGenerator\ServiceProvider"
In order to use the username generator to make unique usernames for your models, they need to use the FindSimilarUsernames
trait. You'll also need a fillable
username column.
use TaylorNetwork\UsernameGenerator\FindSimilarUsernames;
class Model
{
use FindSimilarUsernames;
protected $fillable = [
// other fillable fields...
'username',
];
}
Add the GeneratesUsernames
trait to your model to automatically generate usernames whenever a model is created without one. This will also validate any user provided usernames.
See Generates Usernames Trait Documentation for additional customization options.
use TaylorNetwork\UsernameGenerator\FindSimilarUsernames;
use TaylorNetwork\UsernameGenerator\GeneratesUsernames;
class Model
{
use FindSimilarUsernames;
use GeneratesUsernames;
protected $fillable = [
// other fillable fields...
'username',
];
}
By default, Laravel uses email addresses to login. To use the username to login, you'll have to modify the authentication that Laravel is using, for newer installations using Laravel Jetstream this is relatively easy.
The easiest way to get this working is to use Laravel Fortify as your authentication kit, Jetstream uses this behind the scenes
In config/fortify.php
change the 'username'
value...
[
// ...
'username' => 'username',
// ...
]
See Fortify docs on Customizing User Authentication.
When using the above authentication kits, in order to allow your users to create their own usernames, you can update the CreateNewUser
action.
public function create(array $input)
{
Validator::make($input, [
'name' => ['required', 'string', 'max:255'],
'email' => [
'required',
'string',
'email',
'max:255',
Rule::unique(User::class),
],
'username' => ['string', 'nullable'],
'password' => $this->passwordRules(),
])->validate();
return User::create([
'name' => $input['name'],
'email' => $input['email'],
'username' => $input['username'],
'password' => Hash::make($input['password']),
]);
}
By default the validation rules can be pretty relaxed, as the generator will auto-populate that field if it's missing or not unique.