Fluent Validation Rules With Laravel Hyrule


May 10th, 2022

Fluent Validation Rules With Laravel Hyrule

Laravel Hyrule is an object-oriented, composable, fluent API for writing validations in Laravel:

Hyrule works by providing a builder object that lets you build rules around the expected form fields. These fields can be simple scalar data types and complex arrays and objects. For example, here's a basic rule validating the first name to be a required string with a max length of 255 characters:

1// Initialize a new builder
2$builder = Hyrule::create();
4// Describe your expected input:
6 ->required()
7 ->max(255);
9$rules = $builder->build();
11$validator = Validator::make($data, $rules);

Most forms submit multiple fields and in order to traverse multiple fields you can chain them together using the end() method:

2 ->string('first_name')
3 ->required()
4 ->max(255)
5 ->end()
6 ->string('last_name')
7 ->required()
8 ->max(255)
9 ->end()
10 ->integer('age')
11 ->required()
12 ->min(21)
13 ->max(60)
14 ->end();

Not only can you define validation for scalar fields, this package allows you to validate objects, arrays of scalar fields, and arrays of objects:

2 ->object('nutritional_facts')
3 ->required()
4 ->integer('servings_per_container')
5 ->required()
6 ->min(1)
7 ->end()
8 ->string('serving_size')
9 ->required()
10 ->min(1)
11 ->max(30)
12 ->end()
13 ->object('fat')
14 ->integer('saturated_fat_grams')->end()
15 ->integer('saturated_fat_percent')
16 ->max(100)
17 ->end();
18 ->end();

As you can see in the above example, we've defined an object with properties, including a property that represents another embedded object.

Learn More

You can learn more about this package, get full installation instructions, and view the source code on GitHub. Also, check out the advanced topics to see all the complex features you might need in a production application.

Filed in:

Paul Redmond

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