File validation rule object in Laravel 9.x
Validating things plays a crucial role in any web application. In Laravel, you can validate the incoming request data using the validate()
method. This method accepts an array of validation rules as its first argument. These rules are used to validate the incoming request data.
Now, traditionally, if you want to validate a file, you can use the file
rule. For example, let’s say you want to validate a file named avatar
in the incoming request data, you can do so like so.
$request->validate([
'avatar' => ['file', 'image', 'max:2048'],
]);
As you can tell, here, we’re using the file
rule to validate the incoming file. We are also using the image
and max
rules to validate that the file is an image and its size respectively.
This is fine but in Laravel 9.x, you can use the File
validation rule object to validate the incoming file. This object is a wrapper around the file
rule. So, you can use it like so.
Using the File
validation rule object
Let’s say you want to validate the incoming file named avatar
in the incoming request data that should be an image that shouldn’t be larger than 2MB, you can use the File
validation rule object like so.
$request->validate([
'avatar' => ['required', 'file', File::image()->atMost(2048)],
]);
We can fluently chain supported rules to the File
validation rule object. Here’s one more example.
$request->validate([
'avatar' => [
'required',
File::image()
->atLeast(2 * 1024)
->smallerThan(12 * 1024)
->dimensions(
Rule::dimensions()
->maxWidth(1000)
->maxHeight(500)
)
],
]);
Here are all the supported rules that you can use with the File
validation rule object.
Supported rules
The following methods are available on the rule:
::types
- equivalent to themimetypes
andmimes
rules::image
- equivalent to theimage
ruleexactly
- equivalent to thesize
rulebetween
- equivalent to thebetween
ruleatLeast
- equivalent to themin
ruleatMost
- equivalent to themax
rulelargerThan
- equivalent to themin
rule + 1kbsmallerThan
- equivalent to themax
rule - 1kbdimensions
- only available after calling::image
, allows specifyingRule::dimensions()
constraints
Defining File::defaults()
rules
If you want to use the default rules that are used by the File
validation rule object, you can define the File::defaults()
method in the boot
method of your application’s AppServiceProvider
like so.
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rules\File;
public function boot()
{
File::defaults(
fn (): File => File::image()
->types(['png', 'jpeg', 'jpg'])
->atMost(2048);
);
}
And then, you can use it when validating the incoming request data like so.
$request->validate([
'avatar' => ['required', File::defaults()],
]);
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.