Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel validation unique

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.

like image 248
Dvir Levy Avatar asked Dec 05 '25 04:12

Dvir Levy


1 Answers

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')
like image 85
Mahdi Younesi Avatar answered Dec 07 '25 19:12

Mahdi Younesi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!