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. For example, if you want to limit the size of a file to 2 megabytes (MB), you can use the following rule:

<?php

$request->validate([
  'file' => 'required|file|size:2048',
]);

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.

You can also specify the maximum file size in bytes, if you prefer. For example, to limit the file size to 2 MB, you can use the following rule:

<?php

$request->validate([
  'file' => 'required|file|size:2097152',
]);

This will validate that the file is required, is a file, and has a size less than or equal to 2 MB (which is equal to 2097152 bytes).

If the file exceeds the specified size, the validation will fail and an error message will be added to the request object. You can then display this error message to the user if necessary.