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 themimetypesandmimesrules::image- equivalent to theimageruleexactly- equivalent to thesizerulebetween- equivalent to thebetweenruleatLeast- equivalent to theminruleatMost- equivalent to themaxrulelargerThan- equivalent to theminrule + 1kbsmallerThan- equivalent to themaxrule - 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()],
]);
👋 Hi there! This is Amit, again. I write articles about all things web development. If you enjoy my work (the articles, the open-source projects, my general demeanour... anything really), consider leaving a tip & supporting the site. Your support is incredibly appreciated!