2

I want to store the file array but i have some problem,this is my html code

<div>
<input type="file" name tmp[]></input>
<textarea name="text[]"></textarea>
</div>
<div>
<input type="file" name tmp[]></input>
<textarea name="text[]"></textarea>
</div>

and my controller

foreach ($request->input('text') as $key => $step){
$data = new Step;
if($request->hasFile('tmp[$key]'){
$file = $request->tmp[$key];
    $extension = $file->getClientOriginalExtension();
    $file_name = strval(time()).str_random(5).'.'.$extension;

    $destination_path = public_path().'/step-upload/';
    $data->img_url = $file_name;
    $upload_success = $file->move($destination_path, $file_name);

}
$data->text=$step;

but it didn't work, i find out that api didn't support hasFile(array),it only support hasFile( string $key)

and also i remove if($request->hasFile('tmp[$key]'){} but find out that no matter how many input file in there,it only catch the first one. Is there any solution?

陳立強
  • 23
  • 1
  • 6

1 Answers1

7

Asuming your HTML is actually correct and that your using the correct enctype on your form.

Laravel uses its dot annotation function in the hasFile function. So what you want to do is to use ('tmp.' . $key) instead of 'tmp[$key]' (which is incorrect, read up opon double vs single quotes).

So, your code should look like this:

foreach ($request->input('text') as $key => $step) {
    if ($request->hasFile('tmp.' . $key)) {
        $file = $request->file('tmp.' . $key);
        // work with $file
    }
}
Community
  • 1
  • 1
Marwelln
  • 28,492
  • 21
  • 93
  • 117