Field UNIQUE (already taken) in edit?

2019-07-10 15:15发布

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>

2条回答
该账号已被封号
2楼-- · 2019-07-10 15:34

You can check this validation

if($user->business_user){
  $this->validate($request,[
    'company_name' => 'required|unique:business_users,'.$user->id
  ]);
}
查看更多
迷人小祖宗
3楼-- · 2019-07-10 15:41

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

查看更多
登录 后发表回答