Skip to content

GeneratesUsernames Trait

Sam Taylor edited this page Aug 2, 2022 · 1 revision

The GeneratesUsernames trait is super useful to get you up and running quickly.

Setup

Include it in your model:

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

class User
{
	use FindSimilarUsernames;
	use GeneratesUsernames;
}

Modify Config

You can override the config by adding a generatorConfig method to your model.

use TaylorNetwork\UsernameGenerator\FindSimilarUsernames;
use TaylorNetwork\UsernameGenerator\GeneratesUsernames;
use TaylorNetwork\UsernameGenerator\Generator;

class User
{
	use FindSimilarUsernames;
	use GeneratesUsernames;

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

The generatorConfig method gets the instance of the Generator method to be used for this class, passed by reference.

Modify Input Before Sending to Generator

To modify any input before sending it to the generator, create a getField method.

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

class User
{
	use FindSimilarUsernames;
	use GeneratesUsernames;

	protected $fillable = [
		'first_name',
		'last_name',
	];

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

In this example, if your user model has a separate first and last name, you can use the getField method to combine them and it will send to the generator.

Using a Different Field Name

If your model is going to use a different field name than the default, you can either use the field map config to update or add a generatorFieldName method to your model.

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

class User
{
	use FindSimilarUsernames;
	use GeneratesUsernames;

	protected $fillable = [
		'fullName',
	];

	public function generatorFieldName(): string
	{
		return 'fullName';
	}
}

Next (Custom Drivers)

Clone this wiki locally