![generating-incremental-usernames-780x439.png](https://pineco.de/wp-content/uploads/2021/09/generating-incremental-usernames-780x439.png)
After we are working with customers or posts, one of many options that we regularly want is producing usernames or slugs. Nevertheless dealing with duplications robotically just isn’t at all times simple. Let’s see how can we use a quite simple answer: producing incremental usernames.
Producing Usernames When Persisting a Mannequin
Let’s say we need to generate a username (or a slug) from the person’s title robotically when storing the mannequin into the database. Usually, it’s not that huge deal, we will use a easy Eloquent occasion callback and the Str::slug() helper.
class Person extends Authenticatable implements MustVerifyEmail
{
protected static perform booted(): void
{
static::creating(static perform (self $person): void {
$user->username = Str::slug($user->title, '.');
});
}
}
For slugs, usually we use – as a separator, however for usernames it’s extra doubtless a ..
This code works properly, and it’s clear and expressive. Nevertheless what if there are two customers with the identical title? The usernames must be distinctive.
Producing Incremental Usernames
With a quite simple regex sample, we will simply monitor the same usernames within the database, and add, or increment a numeric suffix to the username. Let’s check out the code and replace the creating callback within the mannequin.
protected static perform booted(): void
{
static::creating(static perform (self $person): void {
$user->username = static::generateUniqueUsername(
Str::slug($user->title, '.')
);
});
}
protected static perform generateUniqueUsername(string $worth): string
{
$username = static::question()
->the place('username', 'regexp', preg_quote($worth).'[d]?$')
->orderByDesc('username')
->take(1)
->worth('username');
$quantity = (int) filter_var($username, FILTER_SANITIZE_NUMBER_INT);
return $quantity === 0 ? $worth : $worth.++$quantity;
}
Be aware, in MySQL we have to use double-backslash: .
Within the code, we’re trying to find the “newest” username that matches with the presently generated one, and provides or increments a numeric prefix if wanted. So it robotically generates the next sample: username, username1, username2, username3, and so forth.
Closing Ideas
It is a quite simple answer and for easier functions ought to work properly. Nevertheless, whenever you want a extra complicated answer for slugs or usernames, you may lengthen this answer or pull in a bundle.