I have a <form>
where it is possible to upload multiple files. The multiple files should be stored in a different table but for some reason the files are not stored in the database
.
Here is the form:
<form method="POST" action="{{ route('application.store') }}" id="form" enctype="multipart/form-data">
<input name="name" type="text" />
<input name="email" type="text" />
<input name="phone" type="text" />
<input name="additional_files" type="file" multiple />
</form>
Then in my controller I have this:
public function store()
{
$validator = Validator::make(
request()->all(),
[
'email' => ['required', 'email'],
'name' => ['required', 'string'],
'phone' => ['required', 'string']
],
);
if ($validator->fails()) {
return response()
->json($validator->messages(), 400);
}
$application = Application::create([
'email' => request()->email,
'name' => request()->name,
'phone' => request()->phone,
]);
if (request()->hasFile('additional_files')) {
$files = request()->file('additional_files');
foreach ($files as $file) {
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$filesize = $file->getSize();
$path = Storage::disk('local')->put('attachments', request()->file($filename));
$attachment_file = ApplicationFile::create([
'files_id' => $application->id,
'application_id' => $application->id,
'attachment' => $path,
'attachment_name' => $extension,
'attachment_size' => $filesize,
]);
new ApplicationFile($attachment_file);
}
}
}
My model for the files looks like this:
class SingleApplicationFile extends Model {
protected $table = "additional_files";
protected $fillable = [
'attachment', 'files_id', 'attachment_name',
'attachment_size', 'application_id'
];
public function files()
{
return $this->belongsTo('App\Application');
}
}
Then it gets posted with JS:
var additional_files = [];
$("#form input[name='additional_files']").change(
function() {
additional_files = [];
for (var i = 0; i < $(this)[0].files.length; i++) {
additional_files.push($(this)[0].files[i]);
}
}
);
$('#form button[type="submit"]').click(function(e) {
e.preventDefault();
var formData = new FormData();
formData.append(
"name",
$("#form")
.find('input[name="name"]')
.val()
);
formData.append(
"email",
$("#form")
.find('input[name="email"]')
.val()
);
formData.append(
"phone",
$("#form")
.find('input[name="phone"]')
.val()
);
if (additional_files.length > 0) {
formData.append("additional_files", additional_files);
}
axios
.post($("#form").attr("action"), formData)
.then(response => {
// some success message
}
})
.catch(error => {
console.log("ERR: ", error);
});
});
The "regular" fields get stored like they should, but the uploaded files don't stored and when I do dd($request()->all())
it returns:
additional_files: [object File], [object File] // for each file
I have no clue what I'm doing wrong. I tried to add additional_files[]
on the input -> <input type="file" name="additional_files[]" />
but with no luck.
Can someone help me out?