Field UNIQUE (already taken) in edit?

倾然丶 夕夏残阳落幕 提交于 2019-12-11 03:08:59

问题


I have problem with validate when i edit my user. So when i edit i get message that name is already taken. How can i fix this? Because that name belongs to that user. So i need to change name again so that i can edit my user.

    if($user->business_user){
      $this->validate($request,[
        'company_name' => 'required|unique:business_users'
      ]);
    }

My view:

<div class="col-md-6 col-sm-6 col-xs-12">
   <div class="form-group" v-bind:class="{ 'has-error': basic_errors.company_name }">
         <label class="form_title">COMPANY NAME</label>
         <input type="text" name="company_name" v-model="basic_credentials.company_name" value="{{ is_value_empty($user->business_user->company_name) }}" class="form_input">
         <span class="help-block" id="helpBlock2" v-show="basic_errors.company_name">@{{ basic_errors.company_name }}</span>
   </div>
</div>

回答1:


You can check this validation

if($user->business_user){
  $this->validate($request,[
    'company_name' => 'required|unique:business_users,'.$user->id
  ]);
}



回答2:


Sometimes, you may wish to ignore a given ID during the unique check. For example, consider an "update profile" screen that includes the user's name, e-mail address, and location. Of course, you will want to verify that the e-mail address is unique. However, if the user only changes the name field and not the e-mail field, you do not want a validation error to be thrown because the user is already the owner of the e-mail address.

To instruct the validator to ignore the user's ID, we'll use the Rule class to fluently define the rule. In this example, we'll also specify the validation rules as an array instead of using the | character to delimit the rules:

Validator::make($data, [
    'email' => [
        'required',
        Rule::unique('users')->ignore($user->id),
    ],
]);

https://laravel.com/docs/5.3/validation#rule-unique



来源:https://stackoverflow.com/questions/41829840/field-unique-already-taken-in-edit

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