Laravel用户名如果​​已经被带走了

时间:2018-04-21 11:28:57

标签: laravel registration user-registration

我想进行用户注册,以便如果用户注册了姓名,请说" John"并且已经使用了这个用户名,他获得了用户名" John2",如果" John2"他也得到了#3; John3"等

我可以制作某种循环来检查用户名是否被占用并生成新的用户名。但效率不高。

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

使用此功能:在参数中传递用户名,并根据您的数据库获取唯一名称

public function generateUniqueUserName($username)
    {
        $username = strtolower($username);
        $variations = 0;

        while (true) {
            $newUserName = $username;
            if ($variations > 0) {
                $newUserName .= (string) $variations;
            }
            $userExist = User::where('username', $newUserName)->exists();

            if ($userExist) {
                $variations++;
            } else {
                $username = $newUserName;
                break;
            }
        }

        return $username;
    }

答案 1 :(得分:-1)

请尝试以下解决方案,

$username = \Str::slug('John');
$userRows  = User::whereRaw("username REGEXP '^{$username}([0-9]*)?$'")->pluck('username')->toArray();
if(count($userRows) > 0) {
  $userRows = str_replace($name, '', $userRows);
  $i=1;
  while(in_array($i, $userRows)) {
     $i++;
  }
  $username = $username.$i;
}
echo $username;

并将以下内容添加到config / app.php

中的别名数组中
'Str'       => 'Illuminate\Support\Str',

我认为你有'用户'型号,'用户名'作为你的领域,你正在使用' slug'