我在一种情况下,我将不得不上传一些基于用户需求的图片。一个用户可以有1、2或多于3++个子节点。所以我在上传他孩子的照片时使用了for
循环。这是我的表单:
@for($i=1;$i<=$ticket->children_count;$i++)
<div class="form-group">
<label for="">Child {{ $i }} Name:</label>
<input type="text" name="child_name_{{$i}}" value="" required="" class="form-control">
</div>
<div class="form-group">
<label for="">Child {{ $i }} Photo:</label>
<input type="file" name="child_picture_{{$i}}" value="" required="">
</div>
@endfor
我想从后端接收文件,但不知何故我得到null。以下是控制器内部的for
循环:
for ($i=1; $i <= $ticket->children_count ; $i++) {
$file = $request->file("child_picture_.$i");
dd($request->child_name_.$i);
}
以上代码只返回$i的值。我怎样才能正确地收到文件?必须是child_name_1
或child_name_2
child_picture_1
或child_picture_3
等。
您应该替换以下内容:
dd($request->child_name_.$i);
// php thinks that you are providing two variables:
// $request->child_name_ and $i
:
dd($request->{'child_name_'.$i});
// makes sure php sees the whole part
// as the name of the property
编辑
对于文件,替换为:
$file = $request->file("child_picture_.$i");
:
$file = $request->file("child_picture_" . $i);
不好意思,但是对于多个文件你应该使用数组(可维护性,可读性),像这样:
@for($i=1;$i<=$ticket->children_count;$i++)
<div class="form-group">
<label for="">Child {{ $i }} Name:</label>
<input type="text" name="child_names[]" value="" required="" class="form-control">
</div>
<div class="form-group">
<label for="">Child {{ $i }} Photo:</label>
<input type="file" name="child_pictures[]" value="" required="">
</div>
@endfor
在你的控制器检查请求有这样的文件:
if ($request->hasFile('child_pictures')) {
$files = $request->file('child_pictures');
foreach($files as $file) {
var_dump($file); // dd() stops further executing!
}
}