In Laravel 9.41, we now have a few convenient static constructors added for things like enum rules, files, and image files.
You can construct these rule objects directly, but I like the convenience of knowing I have access to them through static constructors on the main Rule
object:
1use Illuminate\Validation\Rule;
2use Illuminate\Validation\Rules\Enum;
3use Illuminate\Validation\Rules\File;
4use Illuminate\Validation\Rules\ImageFile;
5
6// Before
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);
Here’s a more complete example to see how validation rules look using the main Rule
class static methods:
1use App\Models\Post;
2use Illuminate\Validation\Rule;
3use Illuminate\Validation\Rules\Enum;
4use Illuminate\Validation\Rules\Unique;
5
6// Before
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 don’t have examples in the documentation, and I find these are more discoverable via the main Rule
class methods. If you peek at the rule classes under the Illuminate\Validation\Rules
namespace, it looks like the following at the time of writing:
- DatabaseRule
- Dimensions
- Enum
- ExcludeIf
- Exists
- File
- ImageFile
- In
- NotIn
- Password
- ProhibitedIf
- RequiredIf
- Unique
I’d encourage you to dive into the source to learn more about these useful objects and how they work. The validation docs have helpful examples of how to use some of these rule builders, such as the File
and Exists
to name a few.