How to validate that uploaded file is not empty in case it is less then 1kb?
$request->validate([
'file' => [
'required',
'file',
'extensions:zip',
'max:1024',
'min:1'
]
]);
The validation rule will return error "The file field must be at least 1 kilobytes" on file size 600 bytes.
Does a built in validation exist for file size !=== null?
The problem is that Laravel's min and max rules for files are based on kilobytes, not bytes. So if you set min:1, it actually means the file needs to be at least 1024 bytes. A file that's only 600 bytes will not pass this check.
There's no built-in rule called "min_bytes," but you don't need to create a custom rule class for this.
The easiest way to fix it right away is by using a Closure.
$request->validate([
'file' => [
'required',
'file',
'extensions:zip',
'max:1024', // 1MB
// Custom closure to check file size in bytes
function ($attribute, $value, $fail) {
// $value is an instance of Illuminate\Http\UploadedFile
if ($value->getSize() < 1) {
$fail("The {$attribute} cannot be empty.");
}
},
],
]);
The closure gives you access to the actual UploadedFile object. The getSize() method returns the size in bytes, allowing you to validate that it is truly not empty ( > 0 bytes) without forcing it to be a whole kilobyte.