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();
}
$errorswill be available within the component, so you can do$errors->any()to see whether there are any errors. There's also@error('email') {{ $message }} @enderrorif you want to put the field's error message next to it$this->validate()within a try/catch block -catch ( \Illuminate\Validation\ValidationException $e)within the catch block fire your event and then optionallythrow $e;if you want the standard livewire/laravel validation process to continue.