Issue
I have a table with a unique column. My form validation rules look like this:
return Validator::make($data, [
'nameEN' => 'required|string',
'nameHE' => 'required|string',
'address' => 'required|string|min:10|unique:clients'
]);
My issue is that when I edit a row, I get a validation error if I haven't changed the address column.
My edit function looks like so:
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;
}
If I remove the unique
from my validation rules I risk the chance of getting a mysql error.
How can this be sorted out?
Thank you in advance.
Solution
From the docs:
Sometimes, you may wish to ignore a given ID during the unique check, To instruct the validator to ignore the object's ID
'address' => 'required|string|min:10|unique:clients,address,'.$id
Or you could do that using Rule
class
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')
Answered By - Mahdi Younesi
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.