Fluent Validation Rules With Laravel Hyrule
Published on by Paul Redmond
Laravel Hyrule is an object-oriented, composable, fluent API for writing validations in Laravel:
👋 At @square, we built a library that helps us write complex validation rule-sets in #Laravel
— Bez Hermoso (@BezHermoso) May 3, 2022
We are open-sourcing it: say hello to Hyrule 🔥 https://t.co/K3M51ka93x
🧵 1/9
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:
// Initialize a new builder$builder = Hyrule::create(); // Describe your expected input:$builder->string('first_name') ->required() ->max(255); $rules = $builder->build(); $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:
$builder ->string('first_name') ->required() ->max(255) ->end() ->string('last_name') ->required() ->max(255) ->end() ->integer('age') ->required() ->min(21) ->max(60) ->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:
$builder ->object('nutritional_facts') ->required() ->integer('servings_per_container') ->required() ->min(1) ->end() ->string('serving_size') ->required() ->min(1) ->max(30) ->end() ->object('fat') ->integer('saturated_fat_grams')->end() ->integer('saturated_fat_percent') ->max(100) ->end(); ->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.