Livewire-Laravel-Alpine:在验证错误时发出事件,包括 errorbag​​ 上的所有错误

Livewire-Laravel-Alpine: Emit event on validation errors including all errors on errorbag

我正在做Laravel,Livewire 和AlpineJs 项目,验证通过后可以触发事件,如下代码所示。但是当验证错误发生时,下面的代码 $this->validate(); 将不会 运行.

我如何为验证错误发出事件,以便它可以被 blade 文件捕获以显示如下所示的小通知:

Register.blade.php

<span x-data="{ open: false }" x-init="
    @this.on('validation-error', () => {
        if (open === false) setTimeout(() => { open = false }, 2500);
            open = true;
        })"
    x-show.transition.out.duration.1000ms="open" style="display: none;" class="text-red-500">Error saving!</span>

Register.php

class Register extends Component
{
    public $name = '';
    public $email = '';
    public $password = '';
    public $password_confirmation = '';

    protected $rules = [
        'name' => 'required|min:2',
        'email' => 'required|email|unique:users',
        'password' => 'required|min:6|same:password_confirmation',
    ];

    public function register()
    {
        $this->validate();
        // $this->emitSelf('validation-error');
        // Here I want to emit event for validation error 
        // and also should capable to get errors from errorbag 

        $user = User::create([
            'name' => $this->name,
            'email' => $this->email,
            'password' => Hash::make($this->password),
        ]);

        auth()->login($user);

        // $this->emitSelf('notify-saved');

        return redirect('/');
    }

我也试过了,没成功,执行不到这里

$validator = $this->validate();

        if($validator->fails())
        {
            $this->emitSelf('validation-error');
            return redirect('/register');
                //->withErrors($validator)
                //->withInput();
        }

是的,如评论中所述,可以使用 trycatch 块解决。

您可以在 catch 块中发出事件再次验证它,这样如果发生错误您可以触发事件并获取所有错误包

try {
    $this->validate();
} catch (\Illuminate\Validation\ValidationException $e) {
    $this->emitSelf('notify-error');
    $this->validate();
}