php - laravel,如何在注册后在验证器中设置默认值

标签 php laravel

我想在注册过程中为地区和国家设置默认值?我不想放置隐藏的输入或将其放入数据库或迁移中,我希望它完全在注册功能中设置

 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/

相关文章:

php - 如何创建数据透视表 laravel?

php - 另一个 PHP XML 解析错误 : "Input is not proper UTF-8, indicate encoding!"

php - 找到最长的重复字符串?

php - 如何防止 DOMXPath 扩展 HTML 实体?

mysql - 动态行未使用 Laravel Controller 保存在数据库中

Laravel 5.5 设置迁移文件中整数字段的大小

php - 如何获取网站源作为原始文本 Jquery

php - 输入被重复

Git - 供应商文件夹修改 - .gitignore?

laravel - 用于存储 jpg 的 Docker 卷使用情况