How to upload multiple files in laravel 11
The approach is to send an array from FE
const formData = new FormData();
formData.append('files[]', file, fileName);
const response = await axios.post('/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
});
Above the exact code will depend on what framework is being used. The key part is 'files[]'
. Laravel/Php will now treat it as an array.
Backend, in 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 key.
Can also try $request->files
and $request->all()
for debugging.
Above lack validation
- we should validate the files request input
- validate the filename and extension.
The exact validation rules will depend on your application
December 2024