gpt4 book ai didi

php - Laravel 验证唯一

转载 作者:行者123 更新时间:2023-11-29 04:15:37 25 4
gpt4 key购买 nike

我有一个包含唯一列的表。我的表单验证规则如下所示:

    return Validator::make($data, [
'nameEN' => 'required|string',
'nameHE' => 'required|string',
'address' => 'required|string|min:10|unique:clients'
]);

我的问题是,当我编辑一行时,如果我没有更改地址列,则会收到验证错误。

我的编辑功能是这样的:

public function editPost(Request $request,$id){
$client = new Client();
$client->editValidation($request->all())->validate();
$row = $client->where('id',$id)->get()->first();
$update = array();
if(!empty($request->input("nameEN")) && $request->input("nameEN") != $row->nameEN) $update["nameEN"] = $request->input("nameEN");
if(!empty($request->input("nameHE")) && $request->input("nameHE") != $row->nameHE) $update["nameHE"] = $request->input("nameHE");
if(!empty($request->input("address")) && $request->input("address") != $row->address) $update["address"] = $request->input("address");

if(empty($update)) $message = $this->message("info", "Notic: Client {$row->nameEN} was not updated because nothing was changed.");
else if($client->where("id",$row->id)->update($update)){
$message = $this->message("success", "Client {$row->nameEN} was updated.");
} else {
$message = $this->message("danger", "Error: Client {$row->nameEN} was not updated.");
}
$redirect = redirect("clients");
if(isset($message)) $redirect->with("message",$message);
return $redirect;
}

如果我从我的验证规则中删除 unique,我就有可能遇到 mysql 错误。

如何解决这个问题?

提前谢谢你。

最佳答案

来自docs :

有时,您可能希望在唯一性检查期间忽略给定的 ID,指示验证器忽略对象的 ID

'address'  => 'required|string|min:10|unique:clients,address,'.$id

或者您可以使用 Rule 类来做到这一点

use Illuminate\Validation\Rule;

Validator::make($data, [
'address' => [
Rule::unique('clients')->ignore($id),
]
]);

If your table uses a primary key column name other than id, you may specify the name of the column when calling the ignore method:

'address' => Rule::unique('clients')->ignore($id, 'primary_key')

关于php - Laravel 验证唯一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48855327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com