Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

laravel upload files in many inputs

I'm trying to upload files in 4 inputs files i get the solution from here but the problem the last file4 input file uploaded in all fields in database

in my blade form

{!! Form::file('file1', null,['class'=>'form-control']) !!}
{!! Form::file('file2', null,['class'=>'form-control']) !!}
{!! Form::file('file3', null,['class'=>'form-control']) !!}
{!! Form::file('file4', null,['class'=>'form-control']) !!}

in my controller

$input = $request->all();
    $files =[];
    if ($request->file('file1')) $files[] = $request->file('file1');
    if ($request->file('file2')) $files[] = $request->file('file2');
    if ($request->file('file3')) $files[] = $request->file('file3');
    if ($request->file('file4')) $files[] = $request->file('file4');
    foreach ($files as $file)
    {
        if(!empty($file)){
            $destinationPath = public_path() . '/uploads';
            $filename = $file->getClientOriginalName();
            $file->move($destinationPath, $filename);
        }

    }
    $model = new Project($input);
    $model -> file1 = $filename;
    $model -> file2 = $filename;
    $model -> file3 = $filename;
    $model -> file4 = $filename;
    $model->save();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is because you're accessing $filename outside of the foreach which will means only the last one is used.

You could do something like:

$input = $request->all();
$model = new Project($input);
$hasFiles = false;

foreach (range(1, 4) as $i) {
    $fileId = 'file' . $i;

    if ($request->hasFile($fileId)) {
        $hasFiles = true;

        $file = $request->file($fileId);

        $destinationPath = public_path() . '/uploads';
        $filename = $file->getClientOriginalName();
        $file->move($destinationPath, $filename);

        $model->$fileId = $filename;
    }
}

if ($hasFiles) {
    $model->save();
}

Hope this helps!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...