使用for循环的Laravel多个图像上传
I'm in a situation where I will have to upload some pictures based on user needs. A user may have 1, 2 or more then 3++ children. So I'm using a for
loop while uploading his children images. Here is my form:
@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
I want to receive the file from backend but somehow I'm getting null.
Here is the for
loop inside the controller:
for ($i=1; $i <= $ticket->children_count ; $i++) {
$file = $request->file("child_picture_.$i");
dd($request->child_name_.$i);
}
The above code returns only the value of $i. How do I receive the file properly? It has to be something like child_name_1
or child_name_2
child_picture_1
or child_picture_3
etc.
You should replace the following:
dd($request->child_name_.$i);
// php thinks that you are providing two variables:
// $request->child_name_ and $i
To:
dd($request->{'child_name_'.$i});
// makes sure php sees the whole part
// as the name of the property
Edit
And for the file, replace:
$file = $request->file("child_picture_.$i");
To:
$file = $request->file("child_picture_" . $i);
Excuse me, but for multiple files you should use arrays (maintainability, readability), like this:
@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
And in your controller check the request has file like so:
if ($request->hasFile('child_pictures')) {
$files = $request->file('child_pictures');
foreach($files as $file) {
var_dump($file); // dd() stops further executing!
}
}