Laravel Validator Object-Oriented Wrapper

Packages

November 12th, 2019

valiator-oo-featured.png

The Laravel Validator object-oriented wrapper package by Krzysztof Rewak provides a map of all string rules into chained methods. The builder helps you write object-oriented style rules that translate back into their string counterparts:

1$validator = new ValidationBuilder();
2$validator->validate("email", function (Field $field): void {
3 $field->string()->required()->email(["rfc"])
4});
5 
6$validator->getRules();
7// ["email" => "string|required|email:rfc]

Here’s an example of nested validation rules:

1$validator = new ValidationBuilder();
2$validator->validateEach("tags", function (Field $field): void {
3 $field->array();
4});
5$validator->validateInEach("id", "tags", function (Field $field): void {
6 $field->required()->exists("tags", "id");
7});
8 
9$validator->getRules();
10// ["tags.*:" => "array", "tags.*.id:" => "required|exists:tags,id"]

And finally, you can also use the builder in form requests:

1/**
2 * @return array
3 */
4public function rules(): array
5{
6 $this->builder->validate("email", function (Field $field): void {
7 $field->required()->string()->email()->unique("users", "email");
8 });
9 $this->builder->validate("password", function (Field $field): void {
10 $field->required()->string()->min(6)->confirmed();
11 });
12 
13 return $this->builder->getRules();
14}

You can learn more about this package, get full installation instructions, and view the source code on GitHub at krzysztofrewak/laravel-oop-validator.

This package was submitted to our Laravel News Links section. Links is a place the community can post packages and tutorials around the Laravel ecosystem. Follow along on Twitter @LaravelLinks

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.