Gyaaniguy_
self-made · nerd
code 1 min read December 2024

How to upload multiple files in laravel 11

This shouldn't be hard. But the instrcutions were strangely missing and even chatgpt struggled.

The approach is to send an array from the frontend by appending the field name with [] (files[]). Laravel/Php then treats the request value as an array.

  const formData = new FormData();
  formData.append('files[]', file, fileName);
  const response = await axios.post('/upload', formData, {
      headers: {
          'Content-Type': 'multipart/form-data'
      }
  });

The exact code will depend on what framework is being used. The key part is 'files[]'.

Backend, in a laravel controller:

class UploadController extends Controller
{
    public function store(Request $request)
    {
        $files = $request->file('files');
        foreach ($files as $file) {
            $fileName = $file->getClientOriginalName();
            $fileExtension = $file->getClientOriginalExtension();
        }
    }
}

$files = $request->file('files'); is the key line. You can also try $request->files and $request->all() for debugging.

Validation

The above is missing validation. At a minimum:

  1. Validate the files request input.
  2. Validate each file's mime type, size and extension.
$request->validate([
    'files'   => 'required|array|max:10',
    'files.*' => 'file|mimes:jpg,jpeg,png,pdf|max:5120', // 5 MB per file
]);

The exact validation rules will depend on your application.