我有一个包含唯一列的表。 我的表单验证规则如下所示:
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错误。
如何解决这个问题?
提前谢谢。
答案 0 :(得分:4)
来自docs:
有时,您可能希望在唯一检查期间忽略给定的ID, 指示验证者忽略对象的ID
'address' => 'required|string|min:10|unique:clients,address,'.$id
或者你可以使用Rule
class
use Illuminate\Validation\Rule;
Validator::make($data, [
'address' => [
Rule::unique('clients')->ignore($id),
]
]);
如果您的表使用的主键列名不是id,则可以在调用ignore方法时指定列的名称:
'address' => Rule::unique('clients')->ignore($id, 'primary_key')
答案 1 :(得分:1)
用于验证laravel 5.6上的唯一列:
仅用于按需字段,用作:
unique:table,column,except,idColumn
'address' => 'required|string|min:10|unique:clients,address,'.$id
当您要使用单独的类进行验证时。我将通用类用于添加和更新为:
public function rules()
{
if($this->method() == 'POST')
$address = 'required|string|min:10|unique:clients,address';
else
$address = 'required|string|min:10|unique:clients,address,'.$this->id;
//put a hidden input field named id with value on your edit view and catch it here;
return [
'nameEN' => 'required|string',
'nameHE' => 'required|string',
'address' => $address
];
}