Laravel中表单验证里unique在update时怎么排除当前记录呢?

如下代码:

public function rules()
{
     return [
          'name'=>'unique:roles',
    ];
}

以上代码完成了自动验证name值是否唯一。这在新建一条记录时很有用,但是当更新记录且没有改变name值时,该条验证必定会检测到与自己冲突,怎么在update时排除掉自己呢?

阅读 10.1k
2 个回答

https://laravel.com/docs/5.3/...

Forcing A Unique Rule To Ignore A Given ID:

Sometimes, you may wish to ignore a given ID during the unique check. For example, consider an "update profile" screen that includes the user's name, e-mail address, and location. Of course, you will want to verify that the e-mail address is unique. However, if the user only changes the name field and not the e-mail field, you do not want a validation error to be thrown because the user is already the owner of the e-mail address.

To instruct the validator to ignore the user's ID, we'll use the Rule class to fluently define the rule. In this example, we'll also specify the validation rules as an array instead of using the | character to delimit the rules:

use Illuminate\Validation\Rule;

Validator::make($data, [
    'email' => [
        'required',
        Rule::unique('users')->ignore($user->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:

'email' => Rule::unique('users')->ignore($user->id, 'user_id')

你可以参照:Laravel 更新数据时在表单请求验证中排除自己,检查指定字段唯一性

路由

backend/user/{user}

实例

<?php

namespace App\Http\Requests\Backend\User;

use App\Http\Requests\Request;

class UpdateRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $id = $this->route('user'); //获取当前需要排除的id,这里的 user 是 路由 {} 中的参数
        return [
            'email' => "required|email|unique:users,email,".$id,
        ];
    }
    
}

验证说明

unique:表名,字段,需要排除的ID

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏