我想在注册过程中为地区和国家设置默认值?我不想放置隐藏的输入或将其放入数据库或迁移中,我希望它完全在注册功能中设置
protected function postAdminRegistration(Request $request)
{
/** @var User $user */
$validatedData = $request->validate([
'fname' => 'required|string|max:255',
'lname' => 'required|string|max:255',
'country_id'=>'required|integer|min:1',//here default value ex:2
'region_id'=>'required|integer|min:1',//here default value ex:1
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
]);
try {
$validatedData['password']= bcrypt(array_get($validatedData, 'password'));
$validatedData['activation_code'] = str_random(30).time();
$user=app(User::class)->create($validatedData);
} catch (\Exception $exception) {
logger()->error($exception);
return redirect()->back()->with('message', 'Unable to create new user.');
}
$user->notify(new UserRegisteredSuccessfully($user));
return Redirect::to("users/login_form")->withSuccess('Successfully created a new account. Please check your email and activate your account.');
}
最佳答案
如果默认值不存在,我只会检查重新分配值和空合并。
$validatedData['region_id'] = $validatedData['region_id'] ?? $defaultRegion;
$validatedData['country_id'] = $validatedData['country_id'] ?? $defaultCountry;
通常我不建议通过填充来设置 id,而是设置关系。
$user = app(User::class)->create(array_except($validatedData, ['country_id', 'region_id']));
$region = Region::find($validatedData['region_id']) ?? Region::find($defaultRegion);
$user->region()->save();
关于php - laravel,如何在注册后在验证器中设置默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59554777/