Laravel 6 在注册过程中生成用户名

Posted

技术标签:

【中文标题】Laravel 6 在注册过程中生成用户名【英文标题】:Laravel 6 Generate username during registration process 【发布时间】:2021-06-27 18:33:55 【问题描述】:

我不知道这是否可行。我创建了一个 Laravel 6 项目并添加了 auth.现在我希望程序在注册过程中生成用户名。用户没有任何输入字段来写他们的用户名。该程序应该自动生成。例如,用户名为“test”,用户名可以是 test12345678。基本上,它将是用户名 + 8 个随机数。这是 register.blade.php


<body>
    <br>
    <br>
    <div class="container">
        <div class="row">
            <div class="col-sm"></div>
            <div class="col-sm">
                <div class="text-center">
                    <img src="logo.png"  >
                </div>
                <br><br>
                <div class="text-start">

                </div>

            </div>
            <div class="col-sm">
                <form method="POST" action=" route('register') ">
                    <button type="submit" class="btn btn-primary" id="submitBtn">
                         __('Next') 
                    </button>
            </div>
        </div>
    </div>

    <div class="container">
        <div class="text-start">
            <div class="row">
                <div class="col"></div>

                @csrf
                <br>
                <div class="col-6">
                    <div class="text">
                        <h3>Create your account</h3>
                    </div>
                    <br>
                    <input class="design" id="name" type="text" @error('name') is-invalid @enderror" name="name" value=" old('name') " required autocomplete="name" autofocus placeholder="Name">

                    @error('name')
                    <span class="invalid-feedback" role="alert">
                        <strong> $message </strong>
                    </span>
                    @enderror
                    <br><br>
                    <input class="design" id="email" type="email" @error('email') is-invalid @enderror" name="email" value=" old('email') " required autocomplete="email" placeholder="Email">

                    @error('email')
                    <span class="invalid-feedback" role="alert">
                        <strong> $message </strong>
                    </span>
                    @enderror
                    <br><br>
                    <input class="design" id="password" type="password" @error('password') is-invalid @enderror" name="password" required autocomplete="new-password" placeholder="Password">

                    @error('password')
                    <span class="invalid-feedback" role="alert">
                        <strong> $message </strong>
                    </span>
                    @enderror
                    <br><br>
                    <input class="design" id="password-confirm" type="password" name="password_confirmation" required autocomplete="new-password" placeholder="Confirm Password">

                    </form>
                </div>
                <div class="col"></div>
            </div>
        </div>
    </div>
    <br>
</body>

这是 registerController.php:

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class RegisterController extends Controller

    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    
        $this->middleware('guest');
    

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);
    

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
            'avatar' => 'default.png',
        ]);        
    


我还在用户表中添加了一个名为“用户名”的新列

【问题讨论】:

您似乎没有在这里尝试解决这个问题? 【参考方案1】:

您可以在RegisterControllercreate 方法中将以下内容添加到User::create 调用中。

'username' => $data['name'] . rand(pow(10, 8 - 1), pow(10, 8) -1);

这将采用他们提供的名称并附加 8 个随机数字。

不要忘记将username 添加到User 模型的$fillable 属性中。

protected $fillable = ['name', 'email', 'password', 'avatar', 'username'];

【讨论】:

首先感谢您的回答。其次,我尝试添加您的代码,但出现此错误 Illuminate\Database\QueryException SQLSTATE[HY000]: General error: 1364 Field 'username' doesn't have a default value (SQL: insert into users (name, emailpasswordupdated_atcreated_at) 值(测试,test@gmail.com,$2y$10$JjQbZUAziilZgU4voc58XO48q5lKAPWQ1rXlpKLLunttjYTCQ9L9u,2021-013-31 19:32:21-0-26: 26:25)) @ArianKapllanaj 您是否将它添加到了正确的位置,并且是 username 在您的 protected $fillable 数组中的 User 类中? 哦,我的错。是的,它有效!非常感谢!【参考方案2】:

您可以在RegisterController 中执行此操作,如下所示

/**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
            'username' => $data['name'] . str_pad(mt_rand(1,99999999),8,'0',STR_PAD_LEFT)
            'avatar' => 'default.png',
        ]);        
    

【讨论】:

您好,谢谢您的回答。我将您的代码添加到我的项目中并收到此错误 Illuminate\Database\QueryException SQLSTATE[HY000]: General error: 1364 Field 'username' doesn't have a default value (SQL: insert into users (name, @ 987654325@,passwordupdated_atcreated_at) 值(测试,test@gmail.com,$2y$10$wPMp5ydeTP4hjUal0IUTPeglOPKG1ObwXfRcwU7WIYH5cmLDuJmUW,2021-03-11,2021-03-11,2021-03-31 19:3-34: :41))

以上是关于Laravel 6 在注册过程中生成用户名的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Laravel 中生成和验证随机(和临时)密码?

在 Laravel 项目中创建密码哈希

写语句不能在派生类型的用户定义格式化 I/O 过程中生成新行

在 django 中生成用于通过电子邮件验证用户的验证 URL

在rest api app中生成laravel请求验证的最佳实践

在java中生成6位pin