php - Laravel 验证唯一

标签 php mysql validation laravel-5 laravel-5.6

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

    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/

相关文章:

php - 将perl关联数组转换为JSON并在PHP中读取

php - 我可以对我选择的列进行 MD5 运算吗?

php - 将纯 PHP 代码转换为 codeigniter

Java hibernate 找不到 boolean 值的 validator

validation - Mvc4 RTM 验证抛出错误

php - NGINX使用Slim API框架从子目录重定向到根

php - 如何使用 PHP 代码而不是 HTML 代码导入/包含 CSS 文件?

mysql - 适用于 MariaDB 但在 MySQL 上因语法错误而失败的查询

mysql - 如何在一个查询中使用带有替换的子字符串?

javascript - 类型的 Ajv 自定义错误消息