你好,这是我为用户提供的更新控制器。我想知道如何将这些laravel验证规则仅应用于更新的字段。目前,当我只更新名字时,手机号码也会得到验证。我的姓名字段经过阿尔法验证,电话号码通过正则表达式进行验证。
public function update(Request $request, User $setting)
{
request()->validate([
'name' => ['required', 'alpha','min:2', 'max:255'],
'last_name' => ['required', 'alpha','min:2', 'max:255'],
'mobile'=>['required', 'string','regex:/+(9[976]d|8[987530]d|6[987]d|5[90]d|42d|3[875]d|
2[98654321]d|9[8543210]|8[6421]|6[6543210]|5[87654321]|
4[987654310]|3[9643210]|2[70]|7|1)d{1,14}$/'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users,email,'.$setting->id.''],
]);
$setting->update($request->all());
return Redirect::back()->with('success','User updated successfully');
}
我可以处理电子邮件(唯一(字段,但不能处理其他字段。
考虑到我们在评论中的小聊天,您必须首先从数据库中获取模型,并将请求与模型的属性进行区分。然后,您可以只保留已更改属性的验证规则。
public function update(int $id, Request $request, User $userRepository)
{
$user = $userRepository->find($id);
$changedAttributes = array_diff($request->all(), $user->getAttributes());
$validationRules = array_intersect_key([
'name' => ['required', 'alpha','min:2', 'max:255'],
'last_name' => ['required', 'alpha','min:2', 'max:255'],
'mobile' => ['required', 'string', 'regex:/+(9[976]d|8[987530]d|6[987]d|5[90]d|42d|3[875]d|
2[98654321]d|9[8543210]|8[6421]|6[6543210]|5[87654321]|
4[987654310]|3[9643210]|2[70]|7|1)d{1,14}$/'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users,email,'.$setting->id.''],
], $changedAttributes);
$this->validate($request, $validationRules);
$user->update($changedAttributes);
return Redirect::back()->with('success','User updated successfully');
}