In Laravel 9.41, we now have a couple of handy static constructors added for issues like enum guidelines, information, and picture information.
You possibly can assemble these rule objects straight, however I just like the comfort of understanding I’ve entry to them via static constructors on the primary Rule
object:
1use IlluminateValidationRule;
2use IlluminateValidationRulesEnum;
3use IlluminateValidationRulesFile;
4use IlluminateValidationRulesImageFile;
5
6// Earlier than
7(new File())->default();
8(new ImageFile())->dimensions(
9 Rule::dimensions()->maxWidth(1000)->maxHeight(500)
10);
11new Enum(PostStatus::class);
12
13// As of 9.41
14Rule::file()->default()
15Rule::imageFile()->dimensions(
16 Rule::dimensions()->maxWidth(1000)->maxHeight(500)
17);
18Rule::enum(PostStatus::class);
This is a extra full instance to see how validation guidelines look utilizing the primary Rule
class static strategies:
1use AppModelsPost;
2use IlluminateValidationRule;
3use IlluminateValidationRulesEnum;
4use IlluminateValidationRulesUnique;
5
6// Earlier than
7$request->validate([
8 'status' => [
9 'required',
10 new Enum(PostStatus::class)
11 ],
12 'slug' => [
13 'required',
14 new Unique(Post::class);
15 ],
16]);
17
18// After
19$request->validate([
20 'status' => [
21 'required',
22 // Newly added in 9.41
23 Rule::enum(PostStatus::class)
24 ],
25 'slug' => [
26 'required',
27 // Note: unique has been available for a while
28 Rule::unique(Post::class),
29 ],
30]);
Some rule objects haven’t got examples within the documentation, and I discover these are extra discoverable through the primary Rule
class strategies. In the event you peek on the rule courses beneath the IlluminateValidationRules
namespace, it appears like the next on the time of writing:
- DatabaseRule
- Dimensions
- Enum
- ExcludeIf
- Exists
- File
- ImageFile
- In
- NotIn
- Password
- ProhibitedIf
- RequiredIf
- Distinctive
I might encourage you to dive into the supply to be taught extra about these helpful objects and the way they work. The validation docs have useful examples of the best way to use a few of these rule builders, such because the File
and Exists
to call a couple of.