Noob Coder Noob Coder - 27 days ago 11
PHP Question

laravel multiple image uploads using for loop

Im 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 Im 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 im getting null.
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. Please help

Answer

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);
Comments