Skip to content

Getting Started

Sam Taylor edited this page Aug 2, 2022 · 4 revisions

Installation

This package can be installed via Composer

composer require taylornetwork/laravel-username-generator

Publish Config

To publish the Config to config/username_generator.php

php artisan vendor:publish --provider="TaylorNetwork\UsernameGenerator\ServiceProvider"

Required Setup

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',
	];
}

Automatic Generation

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',
	];
}

Use Usernames to Login

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.

User Registration

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.


Next (Basic Usage)

Clone this wiki locally