I am working on Laravel, Livewire and AlpineJs project, Event can be trigger after validation is passed as shown in code below. But when validation error occurs, code below $this->validate();
will not run.
How can I emit event for validation error, so that it can be caught in blade file to show small notification like below:
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('/');
}
I also tried, but not success, execution doesn't reach here
$validator = $this->validate();
if($validator->fails())
{
$this->emitSelf('validation-error');
return redirect('/register');
//->withErrors($validator)
//->withInput();
}
Yes as mention in comment, it can be solved by using trycatch
block.
You can emit event in catch block again validate it so that if errors occurs you can trigger event as well as get all errorbags
try {
$this->validate();
} catch (\Illuminate\Validation\ValidationException $e) {
$this->emitSelf('notify-error');
$this->validate();
}