billok-lab's avatar

Insert form to database using Form Request Validation with file Upload

Hello guys, how can I insert form to a database using Form Request with file upload in it? when I just insert file without validation it's working but when it comes to validation it's not working.

Help me, please :-(

0 likes
15 replies
drewdan's avatar

Can you post your code to show us what you have done so far?

In my projects, I validate the code, and then in the controller, I manipiulate the validated array to upload the file and return the uploaded file hash to store in the database.

public function store(RequestValidator $request) {
$data = $request->validated();
$data['file'] = $request->store('file') ?? null;

Model::create($data)
return redirect()->route('index');
}
billok-lab's avatar

This is my Controller

public function store(FormRegistrationRequest $request){

    $registration = $request->all();

    $file_skhun = $request->file('skhun');
    $skhun = time().'.'.$file_skhun->getClientOriginalExtension();
    $file_skhun->move(public_path('file_skhun'), $skhun);

    $file_statement = $request->file('statement_letter');
    $statement_letter = time().'.'.$file_statement->getClientOriginalExtension();
    $file_statement->move(public_path('file_statement'), $statement_letter);

    $file_student_report = $request->file('student_report');
    $student_report = time().'.'.$file_student_report->getClientOriginalExtension();
    $file_student_report->move(public_path('file_student_report'), $student_report);

    $pas_photo = $request->file('pas_photo');
    $photo = time() . '.' . $pas_photo->getClientOriginalExtension();
    $pas_photo->move(public_path('images'), $photo);

    Registration::create($registration);
    return redirect('student/dashboard');

This is my Form Request

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    return [
        'name' => 'required',
        'nisn' =>   'required',
        'school' =>  'required',
        'skhun'=> 'required|mimes:pdf|max:2048',
        'statement_letter' => 'required|mimes:pdf|max:2048',
        'student_report' => 'required|mimes:pdf|max:2048',
        'additional_achievement' => 'required',
        'packetC' => 'required',
        'faculty' => 'required',
        'majors.value' => 'required',
        'pas_photo' => 'required|mimes:jpeg,jpg,png|max:2048',
    ];
    $id_user = Auth::user()->getAuthIdentifier();
}

public function messages()
{
    return [
        'name.required' => 'Halaman ini tidak boleh kosong',
        'nisn.required'  => 'Halaman ini tidak boleh kosong',
        'school.required'  => 'Halaman ini tidak boleh kosong',
        'skhun.required'  => 'Silahkan Upload file SKHUN anda',
        'skhun.mimes'  => 'File anda harus dalam bentuk PDF',
        'skhun.size'  => 'File anda tidak boleh melebihi 2 Mb',
        'statement_letter.required'  => 'Silahkan Upload file Surat Pernyataan anda',
        'statement_letter.mimes'  => 'File anda harus dalam bentuk PDF',
        'statement_letter.size'  => 'File anda tidak boleh melebihi 2 Mb',
        'student_report.required'  => 'Silahkan Upload file laporan nilai anda',
        'student_report.mimes'  => 'File anda harus dalam bentuk PDF',
        'student_report.size'  => 'File anda tidak boleh melebihi 2 Mb',
        'additional_achievement.required' => 'Halaman ini tidak boleh kosong',
        'packetC.required' => 'Anda belum memilih salah satu dari pilihan yang ada',
        'faculty.required' => 'Anda belum memilih Fakultas yang anda inginkan',
        'majors.required' => 'Anda belum memilih Jurusan yang anda inginkan',
        'pas_photo.required'  => 'Silahkan Upload foto anda',
        'pas_photo.mimes'  => 'Foto anda harus dalam bentuk JPG, JPEG, PNG',
        'pas_photo.size'  => 'Foto anda tidak boleh melebihi 2 Mb'
    ];
}
drewdan's avatar
drewdan
Best Answer
Level 15
public function store(FormRegistrationRequest $request){

    $registration = $request->validated();

    $file_skhun = $request->file('skhun');
    $skhun = time().'.'.$file_skhun->getClientOriginalExtension();
    $file_skhun->move(public_path('file_skhun'), $skhun);
    $registration['skhun'] = $skhun;

    $file_statement = $request->file('statement_letter');
    $statement_letter = time().'.'.$file_statement->getClientOriginalExtension();
    $file_statement->move(public_path('file_statement'), $statement_letter);
    $registration['statement_letter'] = $statement_letter;

    $file_student_report = $request->file('student_report');
    $student_report = time().'.'.$file_student_report->getClientOriginalExtension();
    $file_student_report->move(public_path('file_student_report'), $student_report);
    $registration['student_report'] = $student_report;

    $pas_photo = $request->file('pas_photo');
    $photo = time() . '.' . $pas_photo->getClientOriginalExtension();
    $pas_photo->move(public_path('images'), $photo);
    $registration['pas_photo'] = $photo;

    Registration::create($registration);
    return redirect('student/dashboard');

Something like that might do the trick?

drewdan's avatar

Oh, you may need to add the path name too, not sure how you have it setup

drewdan's avatar

Are you getting any error messages? Or is it just not storing the file names in the database?

billok-lab's avatar

I already set the path, and I didn't get any error message

billok-lab's avatar

Like I said before, when I upload file without validation it working, but when it comes with validation it not working

drewdan's avatar

can you show me the blade file where you have the form which handles this?

billok-lab's avatar

Here is my blade form

                        <form action="{{route('insert.store')}}" class="form-horizontal" method="POST" enctype="multipart/form-data" id="registration_form">
                            {{csrf_field()}}
                            <div class="card-body">
                                <div class="form-group row">
                                    <label class="col-sm-2 col-form-label">Kode Pendaftaran</label>
                                    <div class="col-sm-10">
                                        <p name="kode_pendaftaran" class="form-control" id="kode_pendaftaran">{{ Auth::user()->registration_code }}</p>
                                    </div>
                                </div>
                                <div class="form-group row">
                                    <label for="inputNama" class="col-sm-2 col-form-label">Nama Lengkap</label>
                                    <div class="col-sm-10">
                                        <input name="name" type="text" class="form-control" id="inputNama" placeholder="Nama Lengkap">
                                        <span class="text-danger">{{ $errors->first('name') }}</span>
                                    </div>
                                </div>
                                <div class="form-group row">
                                    <label for="inputNISN" class="col-sm-2 col-form-label">NISN</label>
                                    <div class="col-sm-10">
                                        <input name="nisn" type="number" class="form-control" id="inputNISN" placeholder="Nomor Induk Siswa Nasional">
                                        <span class="text-danger">{{ $errors->first('nisn') }}</span>
                                    </div>
                                </div>
                                <div class="form-group row">
                                    <label for="inputAsalSekolah" class="col-sm-2 col-form-label">Asal Sekolah</label>
                                    <div class="col-sm-10">
                                        <input name="school" type="text" class="form-control" id="inputAsalSekolah" placeholder="Asal Sekolah">
                                        <span class="text-danger">{{ $errors->first('school') }}</span>
                                    </div>
                                </div>
                                <div class="form-group row">
                                    <label for="inputSKHUN" class="col-sm-2 col-form-label">SKHUN</label>
                                    <div class="col-sm-10">
                                            <input name="skhun" type="file" class="form-control-file" id="skhun">
                                        <span class="text-danger">{{ $errors->first('skhun') }}</span>
                                    </div>
                                </div>
                                <div class="form-group row">
                                    <label for="inputPernyataan" class="col-sm-2 col-form-label">Surat Pernyataan</label>
                                    <div class="col-sm-10">
                                        <input name="statement_letter" type="file" class="form-control-file" id="surat_pernyataan">
                                        <span class="text-danger">{{ $errors->first('statement_letter') }}</span>
                                    </div>
                                </div>
                                <div class="form-group row">
                                    <label for="inputRaport" class="col-sm-2 col-form-label">Raport Sem 2-5</label>
                                    <div class="col-sm-10">
                                        <input name="student_report" type="file" class="form-control-file" id="raport">
                                        <span class="text-danger">{{ $errors->first('student_report') }}</span>
                                    </div>
                                </div>
                                <div class="form-group row">
                                    <label for="inputPrestasi" class="col-sm-2 col-form-label">Prestasi lainnya</label>
                                    <div class="col-sm-10">
                                        <input  name="additional_achievement" type="text" class="form-control" id="inputPrestasi" placeholder="Prestasi lainnya">
                                        <span class="text-danger">{{ $errors->first('additional_achievement') }}</span>
                                    </div>
                                </div>
                                <div class="form-group row">
                                    <label for="inputPaketC" class="col-sm-2 col-form-label">Paket C/Luar Negeri</label>
                                    <div class="col-sm-10">
                                        <select class="form-control select2" style="width: 100%;" name="packetC" value="packetC">
                                            <option value="">--- Default ---</option>
                                            <option id="ya" name="packetC" value="ya">Ya</option>
                                            <option id="tidak" name="packetC" value="tidak">Tidak</option>
                                        </select>
                                        <span class="text-danger">{{ $errors->first('packetC') }}</span>
                                    </div>
                                </div>
                                <div class="form-group row">
                                    <label for="inputFakultas" class="col-sm-2 col-form-label">Fakultas</label>
                                    <div class="col-sm-4">
                                        <select name="faculty" class="form-control select2" style="width: 100%;">
                                            <option value="">--- Pilih Fakultas ---</option>
                                            @foreach($faculty_list as $faculty => $value)
                                                <option name="faculty" value="{{ $faculty }}">{{ $value }}</option>
                                                @endforeach
                                        </select>
                                        <span class="text-danger">{{ $errors->first('faculty') }}</span>
                                    </div>
                                    <label for="inputJurusan" class="col-sm-2 col-form-label">Jurusan</label>
                                    <div class="col-sm-4">
                                        <select name="majors" class="form-control select2" style="width: 100%;" required="required">
                                            <option>--- Pilih Jurusan ---</option>
                                        </select>
                                        <span class="text-danger">{{ $errors->first('majors') }}</span>
                                    </div>
                                </div>
                                <div class="form-group row">
                                    <label for="inputPasPhoto" class="col-sm-2 col-form-label">Pas Photo Formal 3x4</label>
                                    <div class="col-sm-10">
                                        <input name="pas_photo" type="file" class="form-control-file" id="photo">
                                        <span class="text-danger">{{ $errors->first('pas_photo') }}</span>
                                    </div>
                                </div>
                                <div class="form-group row">
                                    <div class="offset-sm-2 col-sm-10">
                                        <div class="form-check">
                                            <input type="checkbox" class="form-check-input" id="check" required>
                                            <label class="form-check-label" for="exampleCheck2">Saya menyatakan bahwa semua keterangan yang telah diisi dalam formulir ini adalah benar</label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <!-- /.card-body -->
                            <div class="card-footer">
                                <div class="row">
                                    <button id="submit" type="submit" class="btn btn-info btn-block btn-flat"
                                            onclick="return confirm('Apakah anda yakin data yang dimasukkan sudah benar?')">Simpan Data</button>
                                </div>
                            </div>
                            <!-- /.card-footer -->
                        </form>
drewdan's avatar

If you put a DD in your controller after the validation, does it contain all you expect it to contain

public function store(FormRegistrationRequest $request){

    $registration = $request->all();
dd($registration);
billok-lab's avatar

Thanks a lot @drewdan finally I figure it out actually your first answer is working but you can't just make the insert code like this

    $registration = $request->validated();
    Registration::create($registration);
    

this is how it works on my project

    $registration = new Registration();
    /** @noinspection PhpUndefinedFieldInspection */
    $registration->name = $request->name;
    /** @noinspection PhpUndefinedFieldInspection */
    $registration->nisn = $request->nisn;
    /** @noinspection PhpUndefinedFieldInspection */
    $registration->school = $request->school;
    /** @noinspection PhpUndefinedFieldInspection */
    $registration->skhun = $request->skhun;
    /** @noinspection PhpUndefinedFieldInspection */
    $registration->statement_letter = $request->statement_letter;
    /** @noinspection PhpUndefinedFieldInspection */
    $registration->student_report = $request->student_report;
    /** @noinspection PhpUndefinedFieldInspection */
    $registration->additional_achievement = $request->additional_achievement;
    /** @noinspection PhpUndefinedFieldInspection */
    $registration->packetC = $request->packetC;
    /** @noinspection PhpUndefinedFieldInspection */
    $registration->faculty = $request->faculty;
    /** @noinspection PhpUndefinedFieldInspection */
    $registration->major = $request->majors;
    /** @noinspection PhpUndefinedFieldInspection */
    $registration->pas_photo = $request->pas_photo;
    /** @noinspection PhpUndefinedFieldInspection */
    $registration->id_user = Auth::user()->getAuthIdentifier();
    $registration->save();
drewdan's avatar

Yeh annoyingly you need to do more with file uploads. You could move the file upload stuff into the validated() class in the validator if you wanted a cleaner controller

so in the FormRegistrationRequest validator you could override the validated method

public function validated() {
$registration = parent::validated();

$file_skhun = $this->file('skhun');
    $skhun = time().'.'.$file_skhun->getClientOriginalExtension();
    $file_skhun->move(public_path('file_skhun'), $skhun);
    $registration['skhun'] = $skhun;

    $file_statement = $this->file('statement_letter');
    $statement_letter = time().'.'.$file_statement->getClientOriginalExtension();
    $file_statement->move(public_path('file_statement'), $statement_letter);
    $registration['statement_letter'] = $statement_letter;

    $file_student_report = $this->file('student_report');
    $student_report = time().'.'.$file_student_report->getClientOriginalExtension();
    $file_student_report->move(public_path('file_student_report'), $student_report);
    $registration['student_report'] = $student_report;

    $pas_photo = $this->file('pas_photo');
    $photo = time() . '.' . $pas_photo->getClientOriginalExtension();
    $pas_photo->move(public_path('images'), $photo);
    $registration['pas_photo'] = $photo;

return $registration;

I have not tested that, but the theory is sound. So your controller can just validate and then create on the model.

Please or to participate in this conversation.