我已经使用Laravel 6默认迁移表和Auth注册控制器创建了注册表单。现在,我想拥有两种类型的帐户,因此我在HTML表单中添加了一个复选框。如果该复选框处于选中状态,则该帐户的类型应与未选中该复选框时的类型不同。
数据库表:
account_types (id, name)
users (id, name, email, password, account_type_id)
HTML
<label class="switch">
<input id="register-toggle-switch" name="account-type" type="checkbox" autocomplete="off" checked onclick="toggleswitch()">
</label>
RegisterController.php
/**
* 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'],
// 'account_type_id' => ['required']
]);
}
/**
* Create a new user instance after a valid registration.
*
* @param array $data
* @return \App\User
*/
protected function create(array $data)
{
if (isset($_POST['account-type']))
{
$account = '1';
}
else if(!isset($_POST['account-type']))
{
$account = '2';
}
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'account_type_id' => $account
]);
}
但是,这不起作用,因为它返回一条错误消息:“一般错误:1364字段'account_type_id'没有默认值”,然后继续显示尝试的查询,该查询根本不包含'account_type_id'或其值。
所以问题是:根据表单中复选框的状态,如何将相应的ID传递到注册查询中?
account_type_id
变量传递$fillable
。在User型号上:
protected $fillable = [
'name', 'email', ... 'account_type_id'
];
protected function create(array $data)
{
$account = null;
if (isset($_POST['account-type']))
{
$account = '1';
}
else if(!isset($_POST['account-type']))
{
$account = '2';
}
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'account_type_id' => $account
]);
}