Laravel 7: How to upload more than one input file in laravel?

Viewed 21

I have three different input file in a form. But when I submit the form it only gets the first input file. How can I upload multiple input file? Here's my code:

Form:

<form action="{{ route('apply.store') }}" method="POST" enctype="multipart/form-data">
    <div class="form-group">
        <label for="">Profile</label>
        <input type="file" name="photo" accept="image/*" required>
    </div>
    <div class="form-group">
        <label for="">NID</label>
        <input type="file" name="nid" accept="image/*" required>
    </div>
    <div class="form-group">
        <label for="">Passport</label>
        <input type="file" name="passport" accept="image/*" required>
    </div>
</form>

Controller:

if ($request->hasFile('photo')) {
    $file = $request->photo ;
    $destination_path = 'files/uploads/';
    $filename = date('Ymdhis'). rand(10,99) . '_' . $file->getClientOriginalName();
    $file->move($destination_path, $filename);
    $apply->photo = $filename;
}
if ($request->hasFile('nid')) {
    $file = $request->nid ;
    $destination_path = 'files/uploads/';
    $filename = date('Ymdhis'). rand(10,99) . '_' . $file->getClientOriginalName();
    $file->move($destination_path, $filename);
    $apply->nid = $filename;
}
if ($request->hasFile('passport')) {
    $file = $request->passport ;
    $destination_path = 'files/uploads/';
    $filename = date('Ymdhis'). rand(10,99) . '_' . $file->getClientOriginalName();
    $file->move($destination_path, $filename);
    $apply->passport = $filename;
}

When I submit the form, it only gets the photo input file only. I have changed the order of input file but every time it only gets the first input field value.

Where should I change my code?

1 Answers

You need to make your input's have array brackets in the name and use the multiple attribute, e.g.:

<input type="file" name="nid[]" multiple required>

Then $request->files->get('nid') will be an array of UploadedFile's.

Related