Laravel 4表单验证在更新表单上应该是唯一的,但是如果不是最新的 [英] Laravel 4 Form Validation should be unique on update form, but not if current

查看:50
本文介绍了Laravel 4表单验证在更新表单上应该是唯一的,但是如果不是最新的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试验证更新的用户个人资料表单,通过该表单验证应该检查该电子邮件是否不存在,但是不考虑用户现有的电子邮件是否仍然存在.

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::post('users/edit/{user}', array('before' => 'admin', 'uses' => 'UserController@update'));

用户模型

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

推荐答案

您的规则编写正确,以便忽略特定的id,但是,在尝试尝试之前,您需要在唯一规则中更新{{{ $id }}}的值验证.

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.

我不一定是这种方法的忠实拥护者,但是假设您的规则是User对象上的静态属性,则可以创建一个静态方法,该方法将合并并返回具有正确值的规则.

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

这篇关于Laravel 4表单验证在更新表单上应该是唯一的,但是如果不是最新的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆