1

how to upload multiple files from different fields in laravel when I try the script below, only one file is uploaded, not all files uploaded to the database

public function store(Request $request)
{
    $request->validate([
        'id_satker' => ['required', 'string', 'max:255'],
        'dipa' => 'required|mimes:pdf,xlx,csv,rar,xlsx,docx,doc,xlsb,pptx,ppt,jpg,png,jpeg|max:3000',
        'sk' => 'required|mimes:pdf,xlx,csv,rar,xlsx,docx,doc,xlsb,pptx,ppt,jpg,png,jpeg|max:3000',
        'lms1' => ['required', 'string', 'max:255'],
        'lms2' => ['required', 'string', 'max:255'],
        'las1' => ['required', 'string', 'max:255'],
        'las2' => ['required', 'string', 'max:255'],
    ]);

    //upload
    $namafiledipa = time().'.'.$request->file('dipa')->extension();
    $namafilesk = time().'.'.$request->file('sk')->extension();
    $dipa = $request->file('dipa')->storeAs('public/uploads/inputans', $namafiledipa);
    $sk = $request->file('sk')->storeAs('public/uploads/inputans', $namafilesk);


    $inputans = Inputan::create([
        'id_satker' => $request->id_satker,
        'dipa' => $namafiledipa,
        'sk' => $namafilesk,
        'lms2' => $request->lms2,
        'las1' => $request->las1,
        'las2' => $request->las2,
    ]);

    return redirect('inputan')->with('success', 'Selamat data berhasil ditambah!');
}
4
  • Bisa aja karena nama filenya sama karena pakai time jadi replace Commented Feb 7, 2020 at 8:47
  • jadi apa solusinya mas? Commented Feb 7, 2020 at 8:48
  • Saya bikin jawabannya dulu ya Commented Feb 7, 2020 at 8:49
  • baik mas terimakasih Commented Feb 7, 2020 at 8:50

1 Answer 1

1

You don't need to use time(), it can have the same value. This will replace your first file $namafiledipa.

$a = time(); // 1581065644
$b = time(); // 1581065644

dd($a, $b);

Laravel automatically generate a unique ID for file name.

try {
    $namafiledipa = $request->file('dipa')->store();
    $namafilesk   = $request->file('sk')->store();
    $inputans     = Inputan::create([
        'id_satker' => $request->id_satker,
        'dipa'      => $namafiledipa,
        'sk'        => $namafilesk,
        'lms2'      => $request->lms2,
        'las1'      => $request->las1,
        'las2'      => $request->las2,
    ]);

    return redirect('inputan')
        ->with('success', 'Selamat data berhasil ditambah!');
} catch (\Exception $e) {
    dd($e);
}

try-catch can help you when something goes wrong.

Sign up to request clarification or add additional context in comments.

3 Comments

Bisa dong di centang :))
sudah dicentang
Terima kasih banyak

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.