The after
event will be triggered after validation is complete. Here you can check the validated data, if validation passed or not, retrieve the error bag and more. This can be handy if you want to log all failed validation to a database i.e.
Like with the before
event, you can use a closure
function or an object class as event handler.
use KrisKuiper\Validator\Blueprint\Events\AfterEvent;
use KrisKuiper\Validator\Validator;
$data = ['email' => 'email@domain.com'];
$validator = new Validator($data);
//Attach a new before event listener
$validator->after(function (AfterEvent $event) {
//Check if validation failed
if($event->failed()) {
//Log all the validated data and errors into the database
$DB->logFailedValidation(
$event->getValidatedData()->toArray(),
$event->errors()
);
}
});
//Attach validation rules
$validator->field('email')->required()->email();
//Execute validation
$validator->execute();
Create a new class CustomAfterHandler
that implements the AfterEventInterface
:
use KrisKuiper\Validator\Blueprint\Contracts\AfterEventInterface;
use KrisKuiper\Validator\Blueprint\Events\AfterEvent;
final class CustomAfterEventHandler implements AfterEventInterface
{
public function handle(AfterEvent $event): void
{
//Check if validation failed
if($event->failed()) {
//Log all the validated data and errors into the database
$DB->logFailedValidation(
$event->getValidatedData()->toArray(),
$event->errors()
);
}
}
}
Use this class in the validation:
use KrisKuiper\Validator\Blueprint\Events\AfterEvent;
use KrisKuiper\Validator\Validator;
$data = ['email' => 'email@domain.com'];
$validator = new Validator($data);
//Attach the after event listener
$validator->loadAfterEvent(new CustomAfterEventHandler());
//Attach validation rules
$validator->field('email')->required()->email();
//Execute validation
$validator->execute();
Note: The after
event is also attachable to blueprint validators.
Go to the previous section.
Go to the next section.