0

我正在使用 Livewire 构建我的 Laravel 项目,并且我还在使用 Fortify 实现安全/身份验证层。

但由于各种原因,我没有使用 Jetstream。话虽如此,Jetstream 显然使用了一些非常有用的功能和技术来完成它的工作,因此本着真正的创造力精神,我“借用”了以下“更新密码”表格作为 Jetstream 如何使用 Livewire 与 Fortify 交互。

这个 HTML 模板是用于构建我的表单的实际 HTML 代码的简化版本,但我已经去掉了所有样式和标签等复杂性,因此我们可以只关注重要的内容:

<!-- update-password-form.blade.php (Livewire Template) -->
<form wire:submit.prevent="updatePassword">
    <input id="current_password" type="password" name="current_password" required="true" />
    <input id="password" type="password" name="password" required="true" />
    <input id="password_confirmation" type="password" name="password_confirmation" required="true" />
    <button type="submit">Change Password</button>
</form>

正如我们所见,Livewire 阻止了表单的默认提交,并将其重定向到updatePassword()Livewire 类中的函数。您可以在此处看到的函数如下所示:

/**
 * Update the user's password.
 *
 * @param  \Laravel\Fortify\Contracts\UpdatesUserPasswords  $updater
 * @return void
 */
public function updatePassword(UpdatesUserPasswords $updater)
{
    $this->resetErrorBag();

    $updater->update(Auth::user(), $this->state);

    $this->state = [
        'current_password' => '',
        'password' => '',
        'password_confirmation' => '',
    ];

    $this->emit('saved');
}

这一切似乎都很好。当我(用户)按下[Change Password]Livewire 时,表单设置为非活动状态(以防止用户重复提交表单),当收到来自 Laravel/Livewire 的响应时,表单再次启用。而且……就是这样。

问题是我提交什么数据并不重要。如果我输入所有正确的值,密码不会更新!如果我输入不正确current_password,它不会出错。如果我提交current_password不匹配的正确passwordpassword_confirmation,我将获得相同的“没有发生”的体验(作为最终用户)。当我检查浏览器开发工具上的“网络”选项卡时,每次都会收到有效的 200 个响应,而没有详细报告任何明显的错误。我知道 PHP 函数正在被调用,因为如果我在其中放置dd($this)样式调试,JSON 响应会返回 Livewire 对象。

所以我的问题是以下......

Fortify 框架如何管理错误,我应该如何捕获它们(在 Livewire 中)给用户一些有用的反馈?

ErrorBag(在第一行代码中重置)是否以某种方式填充到$updater->update()函数中?

此外,我从 Jetstream 项目中复制(抱歉,借用)了这个解决方案。这是否也意味着 Jetstream 界面同样不直观(从最终用户的角度来看)?我在 Jetstream 项目中遗漏了一些更高层次的概念吗?

4

1 回答 1

1

我是愚蠢的。错误包返回到视图,模板中没有显示响应的出口。如果存在错误,我只需要一个条件label(或 aspan或 a div)来显示该字段。

<form wire:submit.prevent="updatePassword">
    <input id="current-password" type="password" name="current_password" required="true" />
    @error('current_password')
    <label id="current-password-err" class="error" for="current-password">{{ $message }}</label>
    @enderror
    <input id="password" type="password" name="password" required="true" />
    @error('password')
    <label id="password-err" class="error" for="password">{{ $message }}</label>
    @enderror
    <input id="password-confirmation" type="password" name="password_confirmation" required="true" />
    @error('password_confirmation')
    <label id="password-confirmation-err" class="error" for="password-confirmation">{{ $message }}</label>
    @enderror
    <button type="submit">Change Password</button>
</form>
于 2021-08-13T18:50:04.957 回答