Laravel 登录和注册:新增注册用字段 1 个改进

在 Laravel 自带的注册功能中,我们需要填写用户名、邮箱、和密码来进行用户注册。

假设我们在注册时还需要填写手机号(不包含验证码)。那么我们应该怎么做呢?

首先在迁移文件中加入对应的数据库字段

// create_users_table.php
$table->string('phone')->unique()->nullable();

接着在App\Http\Controllers\Auth\RegisterController中修改以下代码。

    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name'     => ['required', 'string', 'max:255'],
            'email'    => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'phone'    => ['required', 'string', 'digits:11', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);
    }

    protected function create(array $data)
    {
        return User::create([
            'name'     => $data['name'],
            'email'    => $data['email'],
            'phone'   => $data['phone'],
            'password' => Hash::make($data['password']),
        ]);
    }

最后在 blade 模版中加入对应输入框即可。

<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
    <label for="name" class="col-md-4 control-label">Phone</label>
     <div class="col-md-6">
     <input id="phone" type="text" class="form-control" name="phone" value="{{ old('phone') }}" required autofocus>
        @if ($errors->has('phone'))
            <span class="help-block">
                 <strong>{{ $errors->first('phone') }}</strong>
            </span>
         @endif
    </div>
</div>
本文为 Wiki 文章,邀您参与纠错、纰漏和优化
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!