laravel更新唯一值验证

时间:2014-06-30 13:16:46

标签: php validation laravel laravel-4 blade

我有一个mobileNumber属性的模型。手机号码是唯一的,验证规则是:

public  static  $rulesForEdit = array(
        'firstName' => 'required|min:5',
        'lastName' => 'required|min:5',
        'mobileNumber' => 'required|min:5|unique:admin,mobileNumber|numeric'
    );

当我更新模型时,我这样做:

$data = array('firstName' => Input::get('firstName'),
        'lastName' => Input::get('lastName'),
        'mobileNumber' => Input::get('mobileNumber')
);
$validation = Validator::make($data, Admin::$rulesForEdit);
if($validation->passes()){
    $admin = Admin::find($id);
    $admin->firstName = Input::get('firstName');
    $admin->lastName = Input::get('lastName');
    $admin->mobileNumber = Input::get('mobileNumber');
    $admin->update();
    return Redirect::to("restaurants/admins/".$admin->id);
}else{

    return Redirect::back()->withInput()->withErrors($validation);
}

我不断收到验证错误消息的问题表明:The mobile number has already been taken哪个正确,但移动设备属于我正在更新的同一型号,没有使用此移动电话号码的其他型号,只是我要更新的型号。 换句话说,我正在更新名字和姓氏,但不更新手机号码

1 个答案:

答案 0 :(得分:1)

要强制Validator忽略给定id的唯一规则,您可以传递正在验证的recored的id,例如:

'mobileNumber' => 'required|min:5|numeric|unique:admin,mobileNumber,50'

如果id为10,则不会检查模型的唯一性,因此在更新模型时,需要传递当前模型的id以忽略此模型上的唯一规则:

'mobileNumber' => 'required|min:5|numeric|unique:admin,mobileNumber,' . $id


// Replace the Model with the name of your model within the controller 
// update method before the validation takes place 
Model::$rules['mobileNumber'] = 'required|min:5|numeric|unique:admin,mobileNumber,' . $id;