laravel5.4添加自定义字端保存到表单中

10. August 2017 Laravel 0

第一步:添加字段stdid到users表中

php artisan make:migration add_stdid_to_users_table
然后打开生成的迁移文件,修改up方法
Schema::table('users', function(Blueprint $table)
{
 $table->string('stdid');
});
修改down方法
Schema::table('users', function(Blueprint $table)
{
 $table->dropColumn('stdid');
});
然后运行
php artisan make:migration add_stdid_to_users_table

第二步:打开register.blade.php,添加

<div class="form-group{{ $errors->has('stdid') ? ' has-error' : '' }}">
    <label for="stdid" class="col-md-4 control-label">学号</label>

    <div class="col-md-6">
        <input id="stdid" type="text" class="form-control" name="stdid" value="{{ old('stdid') }}" required autofocus>

        @if ($errors->has('stdid'))
            <span class="help-block">
                <strong>{{ $errors->first('stdid') }}</strong>
            </span>
        @endif
    </div>
</div>

第三步:打开RegisterController.php控制器修改validator和create方法如下

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:6|confirmed',
        'stdid' => 'required|string',
    ]);
}
 protected function create(array $data)
 {
 return User::create([
 'name' => $data['name'],
 'email' => $data['email'],
 'password' => bcrypt($data['password']),
 'stdid' => $data['stdid'],
 ]);
 }

第四步:打开app/User.php,添加stdid字段到$fillable中,如下

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

success