Laravel 登录和注册:新增注册用字段
在 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>
推荐文章: