Validate Max File Size in Laravel, PHP and Web-Server

Tutorial last revisioned on August 11, 2022 with Laravel 9
I got this question at least a dozen times: "I'm raising my file validation rule in Laravel to 20 MB but still get errors, it doesn't work". So decided to expand on it and explain the reason, and what to do. First, let's see how to validate file size in Laravel. In your Form Request files or validate() method you can pass array with this parameter:
  'image' => 'required|mimes:jpeg,bmp,png|size:20000',
The last part means that size should be not more than 20 MB (20000 kB). But that may be not enough, cause file restrictions exist not only on Laravel application level.


Since Laravel 9.22 there's new fluent file validation rule. Above rule can now be written like this
'image' => ['required', File::image()->smallerThan(20000)
You can check pull request for this change here and read updated official documantation here.

PHP settings in php.ini

There are two settings related to max size in php.ini file. Here they are with their default values:
upload_max_filesize = 2M
post_max_size = 8M
As you can see, by default you can upload files only up to 2 MB, so you should change that to 20M. But even that won't allow you to upload 20 MB files, because of overall POST request restriction by post_max_size, it should be set to 20M, or rather even bigger than that, cause POST will likely to have more data than just the file, so I would set it to 21M at least, in that case. Also, please make sure you're editing the correct php.ini file, cause there are cases with multiple files on the same server, for different PHP versions, also for FPM and CLI settings. But even this may be not enough. There's also web-server configuration.

Nginx and Apache Settings

By default Laravel Forge creates servers with LEMP stack, which uses Nginx as a web-server. Even without knowing how to configure it, you need to care about one setting in nginx.conf file: client_max_body_size. Here's a screenshot from official documentation: As you can see, default value is only 1m, which means that your whole POST request may be maximum 1MB. So you need to change that setting to 20m or higher.
If you're using Apache web-server, there's also a setting for that called LimitRequestBody. Here's a screenshot from the docs: The difference here is that Apache doesn't give any restrictions by default. So there's a chance that you will never need to edit this value, but just in case, it's good to know it exists.
So these are my tips on how to upload bigger files in Laravel. Anything I've missed?

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 59 courses (1056 lessons, total 44 h 09 min)
  • 78 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials