我想在注册过程中设置地区和国家的默认值?我不想放置隐藏输入或将其放入数据库或迁移中,我希望它在注册函数中准确设置
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.');
Run Code Online (Sandbox Code Playgroud)
}
我只需检查该值,然后重新分配该值,如果默认值不存在,则将其合并为空。
$validatedData['region_id'] = $validatedData['region_id'] ?? $defaultRegion;
$validatedData['country_id'] = $validatedData['country_id'] ?? $defaultCountry;
Run Code Online (Sandbox Code Playgroud)
通常我不建议通过可填充项设置 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($region);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30625 次 |
| 最近记录: |