具有属性唯一验证规则的Laravel更新模型


78

我有一个laravelUser模型,该模型对username和具有唯一的验证规则email。在我的存储库中,当我更新模型时,我会重新验证字段,以免所需的规则验证有问题:

public function update($id, $data) {
    $user = $this->findById($id);
    $user->fill($data);
    $this->validate($user->toArray());
    $user->save();
    return $user;
}

测试失败

ValidationException: {"username":["The username has already been taken."],"email":["The email has already been taken."]}

有没有办法优雅地解决这个问题?

Answers:


143

id当前正在更新的实例的追加到验证器。

  1. 传递id实例的来忽略唯一验证器。

  2. 在验证器中,使用参数来检测您是要更新还是创建资源。

如果进行更新,则强制唯一规则忽略给定的id:

//rules
'email' => 'unique:users,email_address,' . $userId,

如果创建,请照常进行:

//rules
'email' => 'unique:users,email_address',

那么,用户ID与电子邮件地址相关还是什么?
乔纳森

好。假设,如果要更新已经存在的电子邮件地址,那么如何找到它?
Vinoth Kumar

请看看这个问题需要帮助stackoverflow.com/questions/39591620/...
阿亚兹·沙阿

4
@ xcy7e웃:laravel.com/docs/5.3/validation unique:table,column,except,idColumn
Luca Filosofi

它仅适用于unique,意味着我已经用过它了lte'order'=> 'lte:products,stock,2'但是为什么不起作用?
Haritsinh Gohil

31

另一种优雅的方式...

在模型中,创建一个静态函数:

public static function rules ($id=0, $merge=[]) {
    return array_merge(
        [
            'username'  => 'required|min:3|max:12|unique:users,username' . ($id ? ",$id" : ''),
            'email'     => 'required|email|unique:member'. ($id ? ",id,$id" : ''),
            'firstname' => 'required|min:2',
            'lastname'  => 'required|min:2',
            ...
        ], 
        $merge);
}

创建时的验证:

$validator = Validator::make($input, User::rules());

更新验证:

$validator = Validator::make($input, User::rules($id));

更新验证,还有一些其他规则:

$extend_rules = [
    'password'       => 'required|min:6|same:password_again',
    'password_again' => 'required'
];
$validator = Validator::make($input, User::rules($id, $extend_rules));

真好


1
非常好!为了使我的工作以这种方式进行,我需要以下几点:'email' => 'required|email|unique:member'. ($id ? ",id,$id" : '')
nickspiel

10

解决我的问题:

public function update($id, $data) {
    $user = $this->findById($id);
    $user->fill($data);
    $this->validate($user->toArray(), $id);
    $user->save();
    return $user;
}


public function validate($data, $id=null) {
    $rules = User::$rules;
    if ($id !== null) {
        $rules['username'] .= ",$id";
        $rules['email'] .= ",$id";
    }
    $validation = Validator::make($data, $rules);
    if ($validation->fails()) {
        throw new ValidationException($validation);
    }
    return true;
}

根据上面接受的答案,我就是这么做的。

编辑:使用表单请求,一切都变得更加简单:

<?php namespace App\Http\Requests;

class UpdateUserRequest 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()
    {
        return [
            'name' => 'required|unique:users,username,'.$this->id,
            'email' => 'required|unique:users,email,'.$this->id,
        ];
    }
}

您只需要将UpdateUserRequest传递给您的更新方法,并确保发布模型ID。


4
您在哪里发布ID?
Norgul '16

8

Laravel中具有不同列ID的唯一验证

'UserEmail'=>"required|email|unique:users,UserEmail,$userID,UserID"

只有这个为我工作。因为在MongoDB中主列是_id,所以其他答案对我不起作用。
AliN11

3

Laravel 5兼容且通用的方式:

我只是遇到了同样的问题,并以一种通用的方式解决了它。如果创建一个项目,它将使用默认规则,如果更新一个项目,它将检查您的规则 :unique并自动插入一个排除项(如果需要)。

创建一个BaseModel类,并让所有模型都继承自该类:

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class BaseModel extends Model {

    /**
     * The validation rules for this model
     *
     * @var array
     */
    protected static $rules = [];

    /**
     * Return model validation rules
     *
     * @return array
     */
    public static function getRules() {
        return static::$rules;
    }

    /**
     * Return model validation rules for an update
     * Add exception to :unique validations where necessary
     * That means: enforce unique if a unique field changed.
     * But relax unique if a unique field did not change
     *
     * @return array;
     */
    public function getUpdateRules() {
        $updateRules = [];
        foreach(self::getRules() as $field => $rule) {
            $newRule = [];
            // Split rule up into parts
            $ruleParts = explode('|',$rule);
            // Check each part for unique
            foreach($ruleParts as $part) {
                if(strpos($part,'unique:') === 0) {
                    // Check if field was unchanged
                    if ( ! $this->isDirty($field)) {
                        // Field did not change, make exception for this model
                        $part = $part . ',' . $field . ',' . $this->getAttribute($field) . ',' . $field;
                    }
                }
                // All other go directly back to the newRule Array
                $newRule[] = $part;
            }
            // Add newRule to updateRules
            $updateRules[$field] = join('|', $newRule);

        }
        return $updateRules;
    }
}    

现在,您可以像以前那样在模型中定义规则:

protected static $rules = [
    'name' => 'required|alpha|unique:roles',
    'displayName' => 'required|alpha_dash',
    'permissions' => 'array',
];

并在您的控制器中对其进行验证。如果模型未通过验证,它将自动重定向回具有相应验证错误的表单。如果没有发生验证错误,它将继续执行之后的代码。

public function postCreate(Request $request)
{
    // Validate
    $this->validate($request, Role::getRules());
    // Validation successful -> create role
    Role::create($request->all());
    return redirect()->route('admin.role.index');
}

public function postEdit(Request $request, Role $role)
{
    // Validate
    $this->validate($request, $role->getUpdateRules());
    // Validation successful -> update role
    $role->update($request->input());
    return redirect()->route('admin.role.index');
}

而已!:)请注意,创建时我们调用Role::getRules(),编辑时我们调用$role->getUpdateRules()


3

或您可以在“表单请求”中执行的操作是(对于Laravel 5.3+)

public function rules()
    {
        return [

            'email' => 'required|email|unique:users,email,'.$this->user, //here user is users/{user} from resource's route url
               ];
    }

我已经在Laravel 5.6中做到了,并且有效。


2

我有BaseModel类,所以我需要一些通用的东西。

//app/BaseModel.php
public function rules()
{
    return $rules = [];
}
public function isValid($id = '')
{

    $validation = Validator::make($this->attributes, $this->rules($id));

    if($validation->passes()) return true;
    $this->errors = $validation->messages();
    return false;
}

假设在用户类中,我只需要验证电子邮件和姓名即可:

//app/User.php
//User extends BaseModel
public function rules($id = '')
{
    $rules = [
                'name' => 'required|min:3',
                'email' => 'required|email|unique:users,email',
                'password' => 'required|alpha_num|between:6,12',
                'password_confirmation' => 'same:password|required|alpha_num|between:6,12',
            ];
    if(!empty($id))
    {
        $rules['email'].= ",$id";
        unset($rules['password']);
        unset($rules['password_confirmation']);
    }

    return $rules;
}

我用phpunit测试了它,效果很好。

//tests/models/UserTest.php 
public function testUpdateExistingUser()
{
    $user = User::find(1);
    $result = $user->id;
    $this->assertEquals(true, $result);
    $user->name = 'test update';
    $user->email = 'ddd@test.si';
    $user->save();

    $this->assertTrue($user->isValid($user->id), 'Expected to pass');

}

我希望可以帮助某人,即使您有更好的主意。也感谢您的分享。(在Laravel 5.0上测试)


2

角色更新的简单示例


// model/User.php
class User extends Eloquent
{

    public static function rolesUpdate($id)
    {
        return array(
            'username'              => 'required|alpha_dash|unique:users,username,' . $id,
            'email'                 => 'required|email|unique:users,email,'. $id,
            'password'              => 'between:4,11',
        );
    }
}       

// controllers/UsersControllers.php
class UsersController extends Controller
{

    public function update($id)
    {
        $user = User::find($id);
        $validation = Validator::make($input, User::rolesUpdate($user->id));

        if ($validation->passes())
        {
            $user->update($input);

            return Redirect::route('admin.user.show', $id);
        }

        return Redirect::route('admin.user.edit', $id)->withInput()->withErrors($validation);
    }

}

1

我正在为存储和更新调用不同的验证类。在我的情况下,我不想更新每个字段,因此我具有用于创建和编辑的通用字段的baseRules。为每个添加额外的验证类。希望我的例子对您有所帮助。我正在使用Laravel 4。

模型:

public static $baseRules = array(
    'first_name' => 'required',
    'last_name'  => 'required',
    'description' => 'required',
    'description2' => 'required',
    'phone'  => 'required | numeric',
    'video_link'  => 'required | url',
    'video_title'  => 'required | max:87',
    'video_description'  => 'required',
    'sex' => 'in:M,F,B',
    'title'  => 'required'
);

public static function validate($data)
{
    $createRule = static::$baseRules;
    $createRule['email'] = 'required | email | unique:musicians';
    $createRule['band'] = 'required | unique:musicians';
    $createRule['style'] = 'required';
    $createRule['instrument'] = 'required';
    $createRule['myFile'] = 'required | image';

    return Validator::make($data, $createRule);
}

public static function validateUpdate($data, $id)
{
    $updateRule = static::$baseRules;
    $updateRule['email'] = 'required | email | unique:musicians,email,' . $id;
    $updateRule['band'] = 'required | unique:musicians,band,' . $id;
    return Validator::make($data, $updateRule);
}

控制器:存储方式:

public function store()
{
    $myInput = Input::all();
    $validation = Musician::validate($myInput);
    if($validation->fails())
    {
        $key = "errorMusician";
        return Redirect::to('musician/create')
        ->withErrors($validation, 'musicain')
        ->withInput();
    }
}

更新方法:

public function update($id) 
{
    $myInput = Input::all();
    $validation = Musician::validateUpdate($myInput, $id);
    if($validation->fails())
    {
        $key = "error";
        $message = $validation->messages();
        return Redirect::to('musician/' . $id)
        ->withErrors($validation, 'musicain')
        ->withInput();
    }
}

1
public static function custom_validation()
{
    $rules = array('title' => 'required ','description'  => 'required','status' => 'required',);
    $messages = array('title.required' => 'The Title must be required','status.required' => 'The Status must be required','description.required' => 'The Description must be required',);
    $validation = Validator::make(Input::all(), $rules, $messages);
    return $validation;
}

1

我有同样的问题。我所做的:只有在我从视图中获得一些ID的情况下,在我的视图隐藏字段中添加一个具有模型ID的模型,并在验证器中检查唯一性。

$this->validate(
        $request,
        [
            'index'       => implode('|', ['required', $request->input('id') ? '' : 'unique:members']),
            'name'        => 'required',
            'surname'     => 'required',
        ]
);

1
'email' => [
    'required',
    Rule::exists('staff')->where(function ($query) {
        $query->where('account_id', 1);
    }),
],

'email' => [
    'required',
    Rule::unique('users')->ignore($user->id)->where(function ($query) {
        $query->where('account_id', 1);
    })
],

其适用于laravel 5.3版本
Anuraag

1
您应该在答案中设置代码格式(我已经为您完成了)。同样,通常,答案不仅应该是没有注释的代码-您可能希望添加简短说明,以说明为什么此特定代码对情况有所帮助。
丹·洛

1

您可以尝试以下代码

return [
    'email' => 'required|email|max:255|unique:users,email,' .$this->get('id'),
    'username' => 'required|alpha_dash|max:50|unique:users,username,'.$this->get('id'),
    'password' => 'required|min:6',
    'confirm-password' => 'required|same:password',
];

你能解释更多吗?
Dieter Meemken

1

如果您还有另一列用作外键或索引,则必须在这样的规则中也指定它。

'phone' => [
                "required",
                "phone",
                Rule::unique('shops')->ignore($shopId, 'id')->where(function ($query) {
                    $query->where('user_id', Auth::id());
                }),
            ],

1

Laravel 5.8简单易用

您可以很好地在表单请求中完成所有操作。。。

首先创建一个字段,您可以通过该字段以普通编辑形式传递ID(不可见)。即

 <div class="form-group d-none">
      <input class="form-control" name="id" type="text" value="{{ $example->id }}" >
 </div>

...然后确保将Rule类添加到表单请求中,如下所示:

use Illuminate\Validation\Rule;

...添加唯一规则,忽略当前ID,如下所示:

public function rules()
{
    return [
          'example_field_1'  => ['required', Rule::unique('example_table')->ignore($this->id)],
          'example_field_2'  => 'required',

    ];

...最后,在update方法中键入提示表单请求的提示与在store方法中一样,如下所示:

 public function update(ExampleValidation $request, Examle $example)
{
    $example->example_field_1 = $request->example_field_1;
    ...
    $example->save();

    $message = "The aircraft was successully updated";


    return  back()->with('status', $message);


}

这样,您就不会不必要地重复代码:-)


1
public function rules()
{
    if ($this->method() == 'PUT') {
        $post_id = $this->segment(3);
        $rules = [
            'post_title' => 'required|unique:posts,post_title,' . $post_id
        ];
    } else {
        $rules = [
            'post_title' => 'required|unique:posts,post_title'
        ];
    }
    return $rules;
}

0

对于自定义的FormRequest和Laravel 5.7+,您可以像这样获取更新后的模型的ID:

public function rules()
    {
        return [
            'name' => 'required|min:5|max:255|unique:schools,name,'.\Request::instance()->id
        ];
    }

0

对于使用表单请求的任何人

以我为例,我尝试了以下所有方法,但均无效果:

$this->id$this->user->id$this->user

这是因为我无法访问模型,$id也无法$id直接访问。

所以我$idunique我尝试验证的相同字段的查询中获得了:

    /**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    $id = YourModel::where('unique_field',$this->request->get('unique_field'))->value('id');
    return [
        'unique_field' => ['rule1','rule2',Rule::unique('yourTable')->ignore($id)],
    ];
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.