2016-11-06 53 views
0

我處於一種情況,我必須根據用戶需要上傳一些圖片。用戶可能有1個,2個或更多個3 ++孩子。所以我在使用for循環的同時上傳他的孩子圖片。這是我的形式:Laravel使用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 

我想從後端接收文件,但不知何故我得到空。 這裏是控制器內的for循環:

for ($i=1; $i <= $ticket->children_count ; $i++) { 
      $file = $request->file("child_picture_.$i"); 
      dd($request->child_name_.$i); 
} 

上面的代碼返回的$我只的值。我如何正確接收文件?它必須像child_name_1child_name_2child_picture_1child_picture_3

回答

0

此時應更換如下:

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); 
+0

這工作的名稱,但如何打印內部$ request-> file()部分? –

+0

查看我更新的答案。 –

+0

非常感謝你..這真的幫了很多 –

0

對不起,但多個文件你應該使用數組(可維護性,可讀性),像這樣:

@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! 
    } 
}