How to Validate on Max File Size in Laravel?
To validate a file size in Laravel, you can use the size rule in your request validation.
To validate a file size in Laravel, you can use the size rule in your request validation. For example, if you want to limit the size of a file to 2 megabytes (MB), you can use the following rule:
Example of using the "size" rule in the request validation to validate a file size in Laravel
<?php
$request->validate([
'file' => 'required|file|size:2',
]);This will validate that the file is required, is a file (as opposed to a string or other type), and has a size less than or equal to 2 MB. Note that for files, the size rule expects the value in megabytes.
You can also specify the maximum file size in bytes using the max rule. For example, to limit the file size to 2 MB (2097152 bytes), you can use the following rule:
Example of using the "max" rule in the request validation to validate a file size in bytes in Laravel
<?php
$request->validate([
'file' => 'required|file|max:2097152',
]);This will validate that the file is required, is a file, and has a size less than or equal to 2 MB.
If the file exceeds the specified size, the validation will fail and an error message will be added to the $errors bag. You can display this error in your Blade view using @error('file') {{ $message }} @enderror, or customize the message by passing an array as the second argument to validate():
$request->validate([
'file' => 'required|file|max:2097152',
], [
'file.max' => 'The file must not exceed 2 MB.',
]);