以下 PHP 代码用于捕获来自 Livewire 表单的输入。该表单会更新用户的密码,对于眼尖的人来说,您可能会发现其中大部分内容来自 Laravel Fortify 框架。
/**
* Validate and update the user's password.
*
* @param mixed $user
* @param array $input
* @return void
*/
public function update($user, array $input)
{
try {
Validator::make($input, [
'current_password' => ['required', 'string'],
'password' => $this->passwordRules(),
])->after(function ($validator) use ($user, $input) {
if (! isset($input['current_password']) || ! Hash::check($input['current_password'], $user->password)) {
$validator->errors()->add('current_password', __('The provided password does not match your current password.'));
}
})->validateWithBag('updatePassword');
} catch (\Illuminate\Validation\ValidationException $e) {
dd ($e);
}
$user->forceFill([
'password' => Hash::make($input['password']),
])->save();
}
如果用户输入无效数据,dd($e);
代码行会显示异常对象。此时抛出的异常对象包含一个名为 的错误包updatePassword
。这是意料之中的,因为validateWithBag()
函数规定应该如此。
到目前为止一切都很好。然而...
如果我尝试在 Livewire 模板(或就此而言,任何 Blade 模板)中捕获错误,命名的错误包就会消失。为了证明这一点,当检测到错误时,<div>
确实会出现以下内容。current_password
@error ('current_password')
<div>Show error here: {{ $message }}</div>
@enderror
但是框架没有显示<div>
以下内容:
@error ('current_password', 'updatePassword')
<div>Show error here: {{ $message }}</div>
@enderror
如果我尝试$errors
从刀片模板本身回显对象,则对象类型不再是 type \Illuminate\Validation\ValidationException
,而是 type Illuminate\Support\ViewErrorBag
。
@php dd($errors); @endphp
也许这是意料之中的。但问题是这个$errors
对象中包含的唯一错误包是'default'
. 错误消息本身是正确的,但它们不在我希望它们在的包中。
为什么是这样?!
这本身并不是一个大问题,但很高兴了解正在发生的事情。随着应用程序的扩展,error-message-id 中的冲突越来越有可能导致意外行为。