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

Cod*_*low 3 php laravel laravel-livewire alpine.js

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

如何发出验证错误事件,以便可以在刀片文件中捕获它以显示如下小通知:

注册.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>
Run Code Online (Sandbox Code Playgroud)

注册.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('/');
    }
Run Code Online (Sandbox Code Playgroud)

我也尝试过,但没有成功,执行不到这里

$validator = $this->validate();

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

小智 5

是的,正如评论中提到的,可以通过使用trycatchblock 来解决。

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

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