Laravel 5.3 multiple file uploads
In Laravel 5.3, you can use the Request
object's file
method to handle multiple file uploads. Here is an example of how you can handle multiple file uploads in a form:
- In your form, make sure the file input field has a
name
attribute set tofiles[]
. This is important as it tells Laravel that the input field is an array of files.
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" name="files[]" multiple>
<input type="submit" value="Upload">
</form>
Watch a video course
Learn object oriented PHP
- In your controller method that handles the form submission, you can use the
Request
object'sfile
method to access the uploaded files. Thefile
method will return an instance of theUploadedFile
class for each file that was uploaded.
<?php
public function upload(Request $request)
{
foreach ($request->file('files') as $file) {
// $file is an instance of UploadedFile
// you can use it to store the file to disk or in the database
}
}
- Now you can move the files to a specific location using the
store
orstoreAs
method provided by theUploadedFile
class
<?php
foreach ($request->file('files') as $file) {
$file->store('public/images');
}
Note: In order to store the files with unique name, you can use storeAs
method and use unique name generator like str_random
foreach ($request->file('files') as $file) {
$file->storeAs('public/images', str_random(20) . '.' . $file->guessExtension());
}
It is also recommended to validate the files before moving it to a specific location using Laravel's validation rules.