Laravel 4 Form Validation should be unique on update form, but not if current

强颜欢笑 提交于 2019-12-02 17:11:00

问题


I am trying to validate an update user profile form, whereby the validation should check that the email doesn't exist already, but disregard if the users existing email remains.

However, this continues to return validation error message 'This email has already been taken'.

I'm really unsure where I'm going wrong. Otherwise, the update form works and updates perfectly.

HTML

 {{ Form::text('email', Input::old('email', $user->email), array('id' => 'email', 'placeholder' => 'email', 'class' => 'form-control')) }}

Route

Route::post('users/edit/{user}', array('before' => 'admin', 'uses' => 'UserController@update'));

User Model

'email' => 'unique:users,email,{{{ $id }}}'

回答1:


Your rule is written correctly in order to ignore a specific id, however, you'll need to update the value of {{{ $id }}} in your unique rule before attempting the validation.

I'm not necessarily a big fan of this method, but assuming your rules are a static attribute on the User object, you can create a static method that will hydrate and return the rules with the correct values.

class User extends Eloquent {
    public static $rules = array(
        'email' => 'unique:users,email,%1$s'
    );
    public static function getRules($id = 'NULL') {
        $rules = self::$rules;
        $rules['email'] = sprintf($rules['email'], $id);
        return $rules;
    }
}



回答2:


You can accomplish this with the sometimes function of the validator

Something like:

$validator->sometimes('email', 'unique:users,email', function ($input) {
    return $input->email == Input::get('email');
});

See http://laravel.com/docs/4.2/validation#conditionally-adding-rules for more info



来源:https://stackoverflow.com/questions/28054979/laravel-4-form-validation-should-be-unique-on-update-form-but-not-if-current

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!