I'm trying to upload files in 4 inputs files i get the solution from here but the problem the last file4 input file uploaded in all fields in database
in my blade form
{!! Form::file('file1', null,['class'=>'form-control']) !!}
{!! Form::file('file2', null,['class'=>'form-control']) !!}
{!! Form::file('file3', null,['class'=>'form-control']) !!}
{!! Form::file('file4', null,['class'=>'form-control']) !!}
in my controller
$input = $request->all();
$files =[];
if ($request->file('file1')) $files[] = $request->file('file1');
if ($request->file('file2')) $files[] = $request->file('file2');
if ($request->file('file3')) $files[] = $request->file('file3');
if ($request->file('file4')) $files[] = $request->file('file4');
foreach ($files as $file)
{
if(!empty($file)){
$destinationPath = public_path() . '/uploads';
$filename = $file->getClientOriginalName();
$file->move($destinationPath, $filename);
}
}
$model = new Project($input);
$model -> file1 = $filename;
$model -> file2 = $filename;
$model -> file3 = $filename;
$model -> file4 = $filename;
$model->save();
This is because you're accessing
$filename
outside of the foreach which will means only the last one is used.You could do something like:
Hope this helps!
If you want to go with this implementation then you should make the
$filename
an array because it will have the value of the last file (when you iterate).Then you can assign from that array:
Maybe a better checking can be made but the idea is to have an array with the uploaded file names.
Thoughts:
I would make a
File
model for the project and declare ahasMany
relation in theProject
and abelongsTo
relation in theFile
model.This would be the correct way to represent your data:
Check out "One To Many" in the docs