【发布时间】:2018-03-21 14:59:51
【问题描述】:
我正在尝试上传多张图片,每张图片都与不同的员工相关联。这是一个示例场景。我有 4 名员工。我想为 2 名员工添加不同的图像,而没有为休息 2 添加任何图像。这是现在发生的情况:
- 如果我不为任何一个添加图像,则所有 4 个都将获得默认图像(这是预期的)
- 如果我为 2 名员工添加不同的图片并留下另外 2 名员工,则所有 4 名员工都会获得最后上传的图片。
- 如果我为 1 名员工添加一张图片,而留下另外 3 张图片,则所有 4 张图片都会获得上传的图片。
对于第 2 和第 3 种情况,我希望为每个员工上传相关图像,如果未上传,则为默认图像。
这是表格:
@if ($employee->payment_option == 2)
<div class="form-group{{ $errors->has('receipt') ? ' has-error' : '' }}">
<input type="file" name="receipt[]" multiple>
@if ($errors->has('receipt'))
<span class="help-block">
<strong>{{ $errors->first('receipt') }}</strong>
</span>
@endif
</div>
@endif
这里是控制器存储方法
public function store(Request $request)
{
if ($request->hasFile('receipt')) {
$files = $request->file('receipt');
foreach ($files as $key => $file) {
$extension = $file->getClientOriginalExtension();
$fileNameWithExt = $file->getClientOriginalName();
$fileName = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
$fileName = $fileName.'_'.time().'.'.$extension;
$folderpath = 'public/images'.'/';
$file->move($folderpath, $fileName);
}
}
foreach ($request->employee_id as $key => $val) {
$payrolls = new Payroll;
$payrolls->employee_id = $val;
if (!empty($request->receipt)) {
$payrolls->receipt = $fileName;
} else {
$payrolls->receipt = 'noimage.jpg';
}
$payrolls->save();
}
return redirect('/');
}
上传多个文件有几个问题,他们的解决方案很好。但是我需要上传与每个员工关联的每个文件。如果没有为员工上传文件,则应附上默认图片。
【问题讨论】:
-
尝试使用
uniqid()或microtime()insted oftime()。 -
谢谢。然而,这不是问题。这仅用于命名文件。与图片上传无关。
标签: php laravel laravel-5.6