doumu1212 2018-08-20 10:51
浏览 60

Laravel 5更新验证电子邮件必须是唯一的

I'm trying to update a user, as an admin.

I'm changing the username, but it says email must be unique.

How do I fix this.

public function update($id, PutUser $request) { if (auth()->id() == $id) { return redirect()->back()->withFlashDanger('Permission Denied, You can not edit own profile here.'); }

$user = User::find($id);


$user->update((array_merge($request->validated(), ['county' => request('county')])));

//Update model_has_roles model with assignees_roles



return redirect()->route('users.index')->withFlashSuccess(trans("alerts.users.updated"));
}

This is the request class

     public function authorize()
     {
         return true;
     }

     public function rules()
     {
         $user_id =  $this->input('id');

         return [
           'name' => 'required|string',
           'username' => 'required',
           'email' => 'required|email|unique:users,email'.$user_id,
           'gender' => 'required',
           'phone' => 'sometimes|numeric',
           'address' => 'sometimes|string',
           'country_id' => 'required',
         ];
     }
}

I keep getting a failed email validation. 'Email has already been taken'. Any idea

  • 写回答

1条回答 默认 最新

  • douchibu7040 2018-08-20 11:14
    关注

    You are missing a comma after the email label in your validation:

    return [
        'name' => 'required|string',
        'username' => 'required',
        'email' => 'required|email|unique:users,email,'.$user_id,
        'gender' => 'required',
        'phone' => 'sometimes|numeric',
        'address' => 'sometimes|string',
        'country_id' => 'required',
    ];
    

    Since Laravel 5.3 (I believe), you can also use rule builders for more descriptive validation rules. Those are better to read and interpret for humans so it would result in a lower error rate:

    use Illuminate\Validation\Rule;
    
    return [
        'email' => [
            'required',
            Rule::unique('users', 'email')->except($user_id),
        ]
    ];
    

    https://medium.com/@tomgrohl/why-you-should-be-using-rule-objects-in-laravel-5-5-c2505e729b40

    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?