问题
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();
回答1:
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:
$input = $request->all();
$model = new Project($input);
$hasFiles = false;
foreach (range(1, 4) as $i) {
$fileId = 'file' . $i;
if ($request->hasFile($fileId)) {
$hasFiles = true;
$file = $request->file($fileId);
$destinationPath = public_path() . '/uploads';
$filename = $file->getClientOriginalName();
$file->move($destinationPath, $filename);
$model->$fileId = $filename;
}
}
if ($hasFiles) {
$model->save();
}
Hope this helps!
回答2:
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).
if(!empty($file)){
$destinationPath = public_path() . '/uploads';
$filename[] = $file->getClientOriginalName();
$file->move($destinationPath, $filename);
}
Then you can assign from that array:
$model = new Project($input);
$model -> file1 = isset($filename[0])?$filename[0]:null;
$model -> file2 = isset($filename[1])?$filename[0]:null;
$model -> file3 = isset($filename[2])?$filename[0]:null;
$model -> file4 = isset($filename[3])?$filename[0]:null;
$model->save();
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 a hasMany
relation in the Project
and a belongsTo
relation in the File
model.
This would be the correct way to represent your data:
foreach($fileEntityList as $fileEntity){
$project->files()->attach($fileEntity);
}
Check out "One To Many" in the docs
来源:https://stackoverflow.com/questions/45075572/laravel-upload-files-in-many-inputs