PHPackages                             taylornetwork/laravel-username-generator - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. taylornetwork/laravel-username-generator

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

taylornetwork/laravel-username-generator
========================================

2.8.0(3y ago)55201.9k↑22.3%92MITPHPPHP ^7.4|^8.0|^8.1

Since Sep 21Pushed 2y ago2 watchersCompare

[ Source](https://github.com/taylornetwork/laravel-username-generator)[ Packagist](https://packagist.org/packages/taylornetwork/laravel-username-generator)[ RSS](/packages/taylornetwork-laravel-username-generator/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (3)Versions (25)Used By (2)

Laravel Username Generator
==========================

[](#laravel-username-generator)

[![GitHub release (latest by date)](https://camo.githubusercontent.com/56e51a7bc906239f02d81f35b17b06d3d3adb1b5d97854e6149e9eaab5f0b994/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f762f72656c656173652f7461796c6f726e6574776f726b2f6c61726176656c2d757365726e616d652d67656e657261746f723f6c6162656c3d72656c6561736526636f6c6f723d626c756576696f6c6574267374796c653d666c61742d737175617265)](https://camo.githubusercontent.com/56e51a7bc906239f02d81f35b17b06d3d3adb1b5d97854e6149e9eaab5f0b994/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f762f72656c656173652f7461796c6f726e6574776f726b2f6c61726176656c2d757365726e616d652d67656e657261746f723f6c6162656c3d72656c6561736526636f6c6f723d626c756576696f6c6574267374796c653d666c61742d737175617265)[![Packagist Downloads](https://camo.githubusercontent.com/0e1d7e0c4c681e2fe8734a24058f4e9a933751fd5ba104384fa00cdbbc0e9b8e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7461796c6f726e6574776f726b2f6c61726176656c2d757365726e616d652d67656e657261746f723f7374796c653d666c61742d73717561726526636f6c6f723d626c7565)](https://camo.githubusercontent.com/0e1d7e0c4c681e2fe8734a24058f4e9a933751fd5ba104384fa00cdbbc0e9b8e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7461796c6f726e6574776f726b2f6c61726176656c2d757365726e616d652d67656e657261746f723f7374796c653d666c61742d73717561726526636f6c6f723d626c7565)[![GitHub](https://camo.githubusercontent.com/0bc10999fc028bce73a9d8049df0adcaeddd8dfb984977dd293e20584a3498bb/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f7461796c6f726e6574776f726b2f6c61726176656c2d757365726e616d652d67656e657261746f723f636f6c6f723d6f72616e6765266c6f676f3d676974687562267374796c653d666c61742d737175617265)](https://camo.githubusercontent.com/0bc10999fc028bce73a9d8049df0adcaeddd8dfb984977dd293e20584a3498bb/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f7461796c6f726e6574776f726b2f6c61726176656c2d757365726e616d652d67656e657261746f723f636f6c6f723d6f72616e6765266c6f676f3d676974687562267374796c653d666c61742d737175617265)[![GitHub branch checks state](https://camo.githubusercontent.com/7da8ae598058b16a00ab0378be4030b5bbfd7271488948a0f336c24dddb0aacd/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f636865636b732d7374617475732f7461796c6f726e6574776f726b2f6c61726176656c2d757365726e616d652d67656e657261746f722f6d61737465723f6c6162656c3d7465737473266c6f676f3d676974687562267374796c653d666c61742d737175617265)](https://camo.githubusercontent.com/7da8ae598058b16a00ab0378be4030b5bbfd7271488948a0f336c24dddb0aacd/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f636865636b732d7374617475732f7461796c6f726e6574776f726b2f6c61726176656c2d757365726e616d652d67656e657261746f722f6d61737465723f6c6162656c3d7465737473266c6f676f3d676974687562267374796c653d666c61742d737175617265)[![StyleCI](https://camo.githubusercontent.com/60047d9a66746d0d34d0915dc175bf411330aa232ed9cd6a417a93e8eed71db5/68747470733a2f2f6769746875622e7374796c6563692e696f2f7265706f732f3130343337303130392f736869656c643f6272616e63683d6d6173746572)](https://camo.githubusercontent.com/60047d9a66746d0d34d0915dc175bf411330aa232ed9cd6a417a93e8eed71db5/68747470733a2f2f6769746875622e7374796c6563692e696f2f7265706f732f3130343337303130392f736869656c643f6272616e63683d6d6173746572)[![Scrutinizer code quality (GitHub/Bitbucket)](https://camo.githubusercontent.com/49989df8f1df94c2e0e113b8035b25cfc132bf9b111805a57c16fa3ef35540fc/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f7175616c6974792f672f7461796c6f726e6574776f726b2f6c61726176656c2d757365726e616d652d67656e657261746f722f6d61737465723f7374796c653d666c61742d737175617265)](https://camo.githubusercontent.com/49989df8f1df94c2e0e113b8035b25cfc132bf9b111805a57c16fa3ef35540fc/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f7175616c6974792f672f7461796c6f726e6574776f726b2f6c61726176656c2d757365726e616d652d67656e657261746f722f6d61737465723f7374796c653d666c61742d737175617265)

Easily generate unique usernames for a Laravel User Model.

Works for Laravel versions above 5.5 including Laravel 9.

1. [Change Log](#change-log)
2. [Install](#install)
3. [Set Up](#set-up)
4. [Config](#config)
    - [Allowed Characters](#allowed-characters)
5. [Basic Usage](#basic-usage)
    - [generate($name)](#generatename)
    - [generateFor($model)](#generateformodel)
    - [GeneratesUsernames Trait](#generatesusernames-trait)
    - [UsernameGenerator Facade](#usernamegenerator-facade)
6. [Other Examples](#other-examples)
    - [With a Separator](#with-a-separator)
    - [Upper Case](#upper-case)
    - [Additional Casing Options](#additional-casing-options)
    - [Mixed Case](#mixed-case)
    - [Minimum Length](#minimum-length)
    - [Maximum Length](#maximum-length)
    - [Other Character Sets](#other-character-sets)
7. [Drivers](#drivers)
    - [Extending](#extending)
8. [License](#license)

Change Log
----------

[](#change-log)

See the [Change Log](https://github.com/taylornetwork/laravel-username-generator/blob/master/CHANGELOG.md)

Install
-------

[](#install)

Via Composer

```
$ composer require taylornetwork/laravel-username-generator
```

### Publish Config

[](#publish-config)

This will add the config to `config/username_generator.php`

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

Quickstart
----------

[](#quickstart)

This section will help you get up and running fast.

The following steps will be the same for all Laravel versions and assumes you're adding the package to a new installation.

**User Model**

In `App\Models\User` (or `App\User` for Laravel 7) add the `FindSimilarUsernames` and `GeneratesUsernames` traits. Add `'username'` to the fillable property.

```
// ...
use TaylorNetwork\UsernameGenerator\FindSimilarUsernames;
use TaylorNetwork\UsernameGenerator\GeneratesUsernames;

class User extends Authenticatable
{
	// ...
	use FindSimilarUsernames;
	use GeneratesUsernames;

	protected $fillable = [
		// ...
		'username',
	];

	// ...

}
```

**Database Migration**

In your `database/2014_10_12_000000_create_users_table` add a username column.

```
class CreateUsersTable extends Migration
{
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            // ...
            $table->string('username')->unique();
            // ...
        });
    }
}
```

### Laravel 8+

[](#laravel-8)

**Note: if you are not using Laravel Jetstream for your project, simply continue with the Laravel 7 guide below.**

Publish the Laravel Fortify config if you haven't already

```
$ php artisan vendor:publish --tag=fortify-config
```

In the `config/fortify.php` change the `'username' => 'email'` to `'username' => 'username'`

```
// ...

'username' => 'username',

'email' => 'email',

// ...
```

Update the login view in `resources/views/auth/login.blade.php` and replace Email with Username.

```

```

### Laravel 7 and below

[](#laravel-7-and-below)

In `config/username_generator.php` update the User model namespace to match your project.

**Using username to login**

To use the username to login instead of the email you need to add the following to your `LoginController`

```
public function username()
{
    return 'username';
}
```

Set Up
------

[](#set-up)

Add the `FindSimilarUsernames` trait on your user model (or whichever model you want to use).

```
use TaylorNetwork\UsernameGenerator\FindSimilarUsernames;

class User extends Authenticatable
{
    use FindSimilarUsernames;
}
```

**Note: this is required in all cases if you want the username to be unique**

Config
------

[](#config)

**This is in the process of being updated on the wiki**

See the [default config](https://github.com/taylornetwork/laravel-username-generator/blob/master/src/config/username_generator.php)

By default the `Generator` class has the following configuration:

ConfigValueTypeUnique Username`true`booleanSeparator`''`string (should be single character)Case`'lower'`string (one of lower, upper, or mixed)Username DB Column`'username'`stringClass`'\App\Models\User'`stringThe config is stored in `config/username_generator.php`

You can override config on a new instance by `new Generator([ 'unique' => false ]);` etc.

### Allowed Characters

[](#allowed-characters)

If you need to include additional characters beyond just `'A-Za-z'` you'll need to update the `allowed_characters` config option.

You should also update `'convert_to_ascii'` to `false` if you want the result to be in the same set.

For example

```
   'allowed_characters' => 'А-Яа-яA-Za-z',   // Would also allow Cyrillic characters

   'allowed_characters' => 'А-Яа-яA-Za-z-_' // Includes Cyrillic, Latin characters as well as '-' and '_'

   'allowed_characters' => '\p{Cyrillic}\p{Greek}\p{Latin}\s ' // Includes cyrillic, greek and latin sets and all spaces

```

Please note that all characters not included in this list are removed before performing any operations. If you get an empty string returned double check that the characters used are included.

Basic Usage
-----------

[](#basic-usage)

#### generate($name)

[](#generatename)

Create a new instance and call `generate($name)`

```
use TaylorNetwork\UsernameGenerator\Generator;

$generator = new Generator();

$username = $generator->generate('Test User');
```

Returns

```
'testuser'
```

If you do not provide a name to the generate method an adjective and noun will be chosen as the name at random, using noun and adjective word lists from [alenoir/username-generator](https://github.com/alenoir/username-generator), which will then be converted to a username.

```
use TaylorNetwork\UsernameGenerator\Facades\UsernameGenerator;

$username = UsernameGenerator::generate();
```

Returns something similar to

```
'monogamousswish'
```

#### generateFor($model)

[](#generateformodel)

Create a new instance and call `generateFor($model)`

This will access the model's `name` property and convert it to a username.

```
use TaylorNetwork\UsernameGenerator\Generator;

class User
{
	public $name = 'Some Other User';

	public function getUsername()
	{
		$generator = new Generator();
		return $generator->generateFor($this);
	}
}
```

Returns

```
'someotheruser'
```

GeneratesUsernames Trait
------------------------

[](#generatesusernames-trait)

This package also comes with a `GeneratesUsernames` trait that you can add to your model and it will automatically call the username generator when the model is saving without the specified username column.

*Note: you will also need to include the `FindSimilarUsernames` trait either way*

```
use TaylorNetwork\UsernameGenerator\GeneratesUsernames;
use TaylorNetwork\UsernameGenerator\FindSimilarUsernames;

class User
{
	use FindSimilarUsernames, GeneratesUsernames;
}
```

You can also add custom config to call before the username is generated.

Override the `generatorConfig` method in your model

```
use TaylorNetwork\UsernameGenerator\GeneratesUsernames;
use TaylorNetwork\UsernameGenerator\FindSimilarUsernames;

class User
{
	use FindSimilarUsernames, GeneratesUsernames;

	public function generatorConfig(&$generator)
	{
		$generator->setConfig([ 'separator' => '_' ]);
	}
}
```

If you need to modify the data before handing it off to the generator, override the `getField` method on your model. For example if you have a first and last name rather than a single name field, you'll need to add this to your model.

```
class User
{
	// ...

	public function getField(): string
	{
		return $this->first_name . ' ' . $this->last_name;
	}

	// ...
}
```

*Note: if your code still uses a custom `getName`, it will still work, however it was replaced with `getField` in v2.1 when driver support was added.*

UsernameGenerator Facade
------------------------

[](#usernamegenerator-facade)

This package includes a `UsernameGenerator` facade for easy access

```
UsernameGenerator::generate('Test User');

UsernameGenerator::generateFor($user);

UsernameGenerator::setConfig([ 'separator' => '_' ])->generate('Test User');
```

Other Examples
--------------

[](#other-examples)

### With a Separator

[](#with-a-separator)

```
$generator = new Generator([ 'separator' => '_' ]);
$generator->generate('Some User');
```

Returns

```
some_user

```

### Upper Case

[](#upper-case)

```
$generator = new Generator([ 'case' => 'upper' ]);
$generator->generate('Some User');
```

Returns

```
SOMEUSER

```

### Additional Casing Options

[](#additional-casing-options)

To change the casing, we make use of the [Laravel String Helpers](https://laravel.com/docs/master/helpers#strings-method-list) so any value that changes the case will work.

**Studly (Pascal)**

```
UsernameGenerator::setConfig([ 'case' => 'studly' ])->generate('test user');
// Returns 'TestUser'
```

When using studly case the laravel helper will remove the spaces between separate words so if a separator is used it will be overridden. You would need to use title case (seen below) in order to have the same effect.

```
UsernameGenerator::setConfig([ 'case' => 'studly', 'separator' => '_' ])->generate('test user');
// Returns 'TestUser'
```

**Title**

This is the same as studly but the laravel helper will not remove spaces, so it can be used in conjunction with a separator

```
UsernameGenerator::setConfig([ 'case' => 'title' ])->generate('test user');
// Returns 'TestUser'

UsernameGenerator::setConfig([ 'case' => 'title', 'separator' => '_' ])->generate('test user');
// Returns 'Test_User'
```

**Ucfirst**

```
UsernameGenerator::setConfig([ 'case' => 'ucfirst' ])->generate('test user');
// Returns 'Testuser'
```

### Mixed Case

[](#mixed-case)

```
$generator = new Generator([ 'case' => 'mixed' ]);
$generator->generate('Some User');
```

Returns

```
SomeUser

```

---

Note: Mixed case will just ignore changing case altogether

```
$generator = new Generator([ 'case' => 'mixed' ]);
$generator->generate('SoMe WeIrD CapitaliZation');
```

Returns

```
SoMeWeIrDCapitaliZation

```

*Note: if you pass an invalid value for the `case` option, mixed case will be used.*

### Minimum Length

[](#minimum-length)

If you want to enforce a minimum length for usernames generated change the `min_length` option in `config/username_generator.php`

```
'min_length' => 6,
```

By default if the generator generates a username less than the minimum length it will pad the end of it with a random digit between 0 and 9.

For example

```
UsernameGenerator::generate('test');

// Would return the following where 0 is a random digit

'test00'
```

**Alternatively you can throw an exception when the minimum length has not been reached**

In `config/username_generator.php` set

```
'throw_exception_on_too_short' => true,
```

```
UsernameGenerator::generate('test');
```

Would throw a `UsernameTooShortException`

### Maximum Length

[](#maximum-length)

If you want to enforce a maximum length for usernames generated change the `max_length` option in `config/username_generator.php`

```
'max_length' => 6,
```

By default if the generator generates a username more than the maximum length it will cut it to the max length value and then try to make it unique again. If that becomes too long it will remove one character at a time until a unique username with the correct length has been generated.

For example

```
UsernameGenerator::generate('test user');

'testus'
```

**Alternatively you can throw an exception when the maximum length has been exceeded**

In `config/username_generator.php` set

```
'throw_exception_on_too_long' => true,
```

```
UsernameGenerator::generate('test user');
```

Would throw a `UsernameTooLongException`

### Other Character Sets

[](#other-character-sets)

Any other character set can be used if it's encoded with UTF-8. You can either include by adding the set to the `'allowed_characters'` option.

Alternatively you can set `'validate_characters'` to `false` to not check.

**You will need to set `'convert_to_ascii'` to `false` either way**

```
$generator = new Generator([
    'allowed_characters' => '\p{Greek}\p{Latin}\s ',
    'convert_to_ascii' => false,
]);

$generator->generate('Αυτό είναι ένα τεστ');

// Returns

'αυτόείναιένατεστ'
```

Drivers
-------

[](#drivers)

2 drivers are included, `NameDriver` (default) and `EmailDriver`

To use a specific driver

```
UsernameGenerator::usingEmail()->generate('testuser@example.com');

// Returns

'testuser'
```

OR

```
$generator = new Generator();
$generator->setDriver('email');
$generator->generate('test.user77@example.com');

// Returns

'testuser'
```

### Extending

[](#extending)

You can make your own custom drivers that extend `TaylorNetwork\UsernameGenerator\Drivers\BaseDriver` or override an existing one.

Custom drivers require a `public $field` property to be set which is the name of the field on the model to use to generate the username.

Drivers will perform the following operations in order:

```
[
	'stripUnwantedCharacters',     // Removes all unwanted characters from the text
	'convertCase',                 // Converts the case of the field to the set value (upper, lower, mixed)
	'collapseWhitespace',          // Collapses any whitespace to a single space
	'addSeparator',                // Converts all spaces to separator
	'makeUnique',                  // Makes the username unique (if set)
]
```

In your custom driver you can add a method to perform an operation before or after any of the above operations.

```
public function beforeConvertCase(string $text): string
{

	// --

}

public function afterStripUnwantedCharacters(string $text): string
{

	// --

}
```

Additionally if there is any operation you want to do as the very first or last thing you can use the first and last hooks.

```
public function first(string $text): string
{
    // Happens first before doing anything else
}

public function last(string $text): string
{
    // Happens last just before returning
}
```

#### Example

[](#example)

For example if you wanted to append `-auto` to all automatically generated usernames, you could make a new driver in `App\Drivers\AppendDriver`

```
namespace App\Drivers;

use TaylorNetwork\UsernameGenerator\Drivers\BaseDriver;

class AppendDriver extends BaseDriver
{
    public $field = 'name';

    public function afterMakeUnique(string $text): string
    {
    	return $text . '-auto';
    }
}
```

And then in `config/username_generator.php` add the driver to the top of the drivers array to use it as default.

```
'drivers' => [
	'append' => \App\Drivers\AppendDriver::class,
        ...
    ],
```

License
-------

[](#license)

See the [License](https://github.com/taylornetwork/laravel-username-generator/blob/master/LICENSE)

###  Health Score

47

—

FairBetter than 94% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity47

Moderate usage in the ecosystem

Community22

Small or concentrated contributor base

Maturity82

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 92.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~80 days

Recently: every ~86 days

Total

23

Last Release

1390d ago

Major Versions

1.1.4 → 2.0.02019-05-08

PHP version history (4 changes)1.0.1PHP ^7.1

2.2.1PHP &gt;=7.1

2.5.0PHP ^7.2|^7.3|^7.4|^8.0

2.6.1PHP ^7.4|^8.0|^8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/83340094473f0bf5b2cf062bf394df221a52a30aa0e21cd0a77302977d6393ce?d=identicon)[samueljtaylor](/maintainers/samueljtaylor)

---

Top Contributors

[![samyrataylor](https://avatars.githubusercontent.com/u/15961687?v=4)](https://github.com/samyrataylor "samyrataylor (153 commits)")[![StyleCIBot](https://avatars.githubusercontent.com/u/11048387?v=4)](https://github.com/StyleCIBot "StyleCIBot (7 commits)")[![pablomadariaga](https://avatars.githubusercontent.com/u/69119357?v=4)](https://github.com/pablomadariaga "pablomadariaga (2 commits)")[![john-climer](https://avatars.githubusercontent.com/u/68661263?v=4)](https://github.com/john-climer "john-climer (1 commits)")[![nikolaynikolaevn](https://avatars.githubusercontent.com/u/50246663?v=4)](https://github.com/nikolaynikolaevn "nikolaynikolaevn (1 commits)")[![timothyasp](https://avatars.githubusercontent.com/u/707699?v=4)](https://github.com/timothyasp "timothyasp (1 commits)")

---

Tags

generatorlaravellaravel-packagelaravel9packagephpphp74php8php80php81usernameusername-generator

### Embed Badge

![Health badge](/badges/taylornetwork-laravel-username-generator/health.svg)

```
[![Health](https://phpackages.com/badges/taylornetwork-laravel-username-generator/health.svg)](https://phpackages.com/packages/taylornetwork-laravel-username-generator)
```

###  Alternatives

[barryvdh/laravel-ide-helper

Laravel IDE Helper, generates correct PHPDocs for all Facade classes, to improve auto-completion.

14.9k123.0M687](/packages/barryvdh-laravel-ide-helper)[orchestra/canvas

Code Generators for Laravel Applications and Packages

20917.2M158](/packages/orchestra-canvas)[illuminate/pipeline

The Illuminate Pipeline package.

9346.6M213](/packages/illuminate-pipeline)[illuminate/pagination

The Illuminate Pagination package.

10532.5M862](/packages/illuminate-pagination)[spatie/laravel-pjax

A pjax middleware for Laravel 5

513371.8k11](/packages/spatie-laravel-pjax)[spatie/laravel-mix-preload

Add preload and prefetch links based your Mix manifest

169176.0k2](/packages/spatie-laravel-mix-preload)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
