我有这个customer
模型,当你创建时有一个unqiue phone_num
。它在create中工作正常但在我的更新函数中,这是一个基于id
的自动填充值的表单。如果用户仅按预期更新了address
,unique
验证将再次触发The phone num has already been taken.
如何处理此问题?如果unique
仍然相同,我希望用户能够更新其忽略phone_num
验证的信息,从而在用户选择更改unique
时允许phone_num
验证}
我的代码:
public function update($id)
{
$rules = array(
'title' => 'required',
'firstname' => 'required',
'lastname' => 'required',
'gender' => 'required',
'birthdate' => 'required',
'age_bracket' => 'required',
'addr1' => 'required',
'addr2' => 'required',
'addr3' => 'required',
'addr4' => 'required',
'town' => 'required',
'country' => 'required',
'postcode' => 'required',
'phone_num' => 'required|unique:customers',
'phone_type' => 'required',
'work_status' => 'required',
'home_status' => 'required',
'marital_status' => 'required',
);
$validator = Validator::make(Input::all(), $rules);
// Check if all fields is filled
if ($validator->fails())
{
return Redirect::to('customer/'.$id.'/edit')->withErrors($validator);
}
else
{
$customer = Customer::find($id);
$customer->title = Input::get('title');
$customer->gender = Input::get('gender');
$customer->firstname = Input::get('firstname');
$customer->lastname = Input::get('lastname');
$customer->postcode = Input::get('postcode');
$customer->addr1 = Input::get('addr1');
$customer->addr2 = Input::get('addr2');
$customer->addr3 = Input::get('addr3');
$customer->addr4 = Input::get('addr4');
$customer->addr4 = Input::get('addr4');
$customer->town = Input::get('town');
$customer->country = Input::get('country');
$customer->phone_num = Input::get('phone_num');
$customer->phone_type = Input::get('phone_type');
$customer->birthdate = Input::get('birthdate');
$customer->work_status = Input::get('work_status');
$customer->home_status = Input::get('home_status');
$customer->marital_status = Input::get('marital_status');
$customer->agebracket = Input::get('age_bracket');
if($customer->save())
{
Session::flash('alert-success', 'Form Submitted Successfully.');
}
else
{
Session::flash('alert-danger', 'Error on submitting form.');
}
return Redirect::to('customer/'.$id.'/edit');
}
}
答案 0 :(得分:12)
unique
规则为此目的采用了一些额外的参数,看起来像unique:table,column,except,idColumn
因此,在您的情况下,except
将是id
,idColumn
将是您的ID列的名称,可能是id
。
因此,考虑到这一点,您希望验证规则为......
'required|unique:customers,phone_num,'.$id.',id'
答案 1 :(得分:2)
在L5.3 +中,您可以使用规则外观流畅地处理它。请注意 验证规则现在将是数组而不是使用|分隔符。 使用Illuminate \ Validation \ Rule;
Validator::make($data, [
'email' => [
'required',
Rule::unique('users')->ignore($user->id),
],
]);
答案 2 :(得分:0)
或者您在表单请求中可以做的是(对于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中做到了,并且奏效了。