arrow_back Return to Posts

Generating Username From First and Last Names
September 2021 ~ Laravel

The idea at its base is to generate unique usernames for each registration using a user’s the first and last names.

Snippet

/**
 * Generate username from the first and last names of user
 *
 * @return $username
 */
function createUserName($first, $last)
{
  $username = trim(strtolower(substr($first, 0, 1).$last));

    if(User::where('username', '=', $username)->exists()) {
      return createUserName($first, $last.rand(1, 5));
    } else {
      return $username;
    }
}

Usage

 $fields['username'] = createUserName($fields['firstName'], $fields['lastName']);

Comments