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

前端 未结 2 672
余生分开走
余生分开走 2021-01-28 05:16

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

2条回答
  •  梦毁少年i
    2021-01-28 05:48

    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;
        }
    }
    

提交回复
热议问题