Search code examples
phplaravellaravel-5.3

Laravel multiple image uploads using for loop


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.


Solution

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