我使用下面的方法更新用户的增值税编号。
但是,当用户在增值税字段中输入某个数字并单击“更新”按钮时,将显示"Undefined variable: countryKey“。
看起来问题在于代码从来不会进入“if ($country == $request->country) {”。但你知道为什么吗?
你知道什么是问题所在吗?
HTML类似于:
<form method="post" action="{{route('user.updateGeneralInfo')}}" class="clearfix">
...
<div class="form-row">
<div class="form-group col-12 col-md-6">
<label for="vat">VAT:</label>
<input type="text" value="{{$user->VAT}}" name="vat" class="form-control"
id="vat"
">
</div>
</div>
...
<div class="form-group col-md-6">
<label for="country">Country</label>
<select class="form-control" name="country" id="country">
@if($user->country)
<option selected="selected">{{$user->country}}</option>
@endif
@foreach($countries as $key => $country)
<option value="{{$key}}">{{ $country}}</option>
@endforeach
</select>
</div>
</form>updateGeneralInfo()如下所示:
public function updateGeneralInfo(Request $request){
$rules = [
'name' => 'required',
'surname' => 'required',
];
$customMessages = [
'name.required' => 'The field name is mandatory.',
'surname.required' => 'The field surname is mandatory.'
];
if (isset($request->vat)) {
$countries = Countries::all(); // get all countries using a package method
// $country is equal to the current $country in the $countries array
while ($country = current($countries)) {
// if the $country is equal to the country selected by the user
if ($country == $request->country) {
dd($country. ' ' .$request->country);
// the $countryKey is the key of the array in the $countries array. For example if the user selects the country "Germany" the $countryKey should be "DE"
$countryKey = (key($countries));
}
// if is not equal continue until it is equal
next($countries);
}
$rules['vat'] = [
function ($attr, $value, $fail) use ($request, $countryKey) {
if (!VatValidator::validateFormat($countryKey . $request->vat)) {
$fail('Please insert a valid VAT.');
}
}];
}
$this->validate($request, $rules, $customMessages);
$user = Auth::user();
$user->name = $request->name;
$user->surname = $request->surname;
$countries = Countries::all();
if($request->country != $user->country){
$user->country = $countries[$request->country];
}
$user->VAT = $request->vat;
$user->save();
Session::flash('general_success', 'Info updated with success.');
return redirect(route('user.index', ['user' => Auth::id()]) . '#generalInfo');
}发布于 2018-07-30 08:49:45
您正在将$countryKey的声明包装在一个if块中。如果该块返回false,则$countryKey不会被定义,或者在您以后调用它时有一个值,并且会出错。在if块外部声明该变量,您的问题就会得到解决。
https://stackoverflow.com/questions/51585733
复制相似问题