nabina khadka
nabina khadka

Reputation: 23

Keep modal open if any validation error exists laravel

I am trying to upload a csv and store the data accordingly in database. Form is in the modal. I want the modal to open if there exists any validation error message.

Here is the modal and ajax query:

    $('#formSubmit').click(function(e) {
    e.preventDefault();
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('input[name="_token"]').val()
        }
    });
    $.ajax({
        url: "{{ url('/resellers') }}",
        type: 'POST',
        contentType: false,
        processData: false,
        data: {
            csv_file: $('#csv_file').val(),
        },
        success: function(result) {
            if (result.errors) {
                $('.alert-danger').html('');
                $.each(result.errors, function(key, value) {
                    $('.alert-danger').show();
                    $('.alert-danger').append('<li>' + value + '</li>');
                });
            } else {
                $('.alert-danger').hide();
                $('#reseller_modal').modal('hide');
            }
        }
    });
});


        <div class="col-sm-6">
        <button type="button" id="csv-import" class="btn btn-secondary m-2 csv-import" data- toggle="modal" data-target="#reseller_modal">Import Csv</button>
    </div>
    <!-- Bootstrap modal -->
    <div class="modal fade" id="reseller_modal" tabindex="-1" role="dialog" aria- labelledby="reseller_modal" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="demoModalLabel">CSV import</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="alert alert-danger" style="display:none"></div>
                <div class="modal-body">
                    <div class="row">
                        <form class="form-horizontal" method="POST" action="{{ route('processImport') }}" enctype="multipart/form-data">
                            {{ csrf_field() }}
                            <div class="form-group">
                                <input id="csv_file" type="file" class="form-control" name="csv_file" required>
                                @if ($errors->has('csv_file'))
                                <span class="help-block">
                                    <strong>{{ $errors->first('csv_file') }}</strong>
                                </span>
                                @endif
                            </div>
                            <div class="form-check">
                            </div>
                            <button type="submit" class="btn btn-primary" id="formSubmit">Submit</button>
                    </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

And here is the controller:

 public function processImport(Request $request)
{
    $validator = Validator::make($request->all(), [
        'csv_file' => 'required|file|mimes:csv,txt'
    ]);
    if ($validator->fails()) {
        return response()->json(['errors' => $validator->errors()->all()]);
    }
    $rows = importCsv($request->file('csv_file'));
    foreach ($rows as $data) {
        $validator = Validator::make($data, [
            'name' => ['required', 'string'],
            'email' => ['required', 'string', 'email'],
            'password' => ['required', 'string'],
        ]);
        $status = User::where('email', '=', $data['email'])->exists();
        if (!$validator->fails()) {
            if (!$status) {
                User::create([
                    'name' => $data['name'],
                    'email' => $data['email'],
                    'password' => bcrypt($data['password'])
                ]);
            } else {
                $user = User::where('email', '=', $data['email'])->first();
                $user->update([
                    'password' => $data['password']
                ]);
            }
        } else {
           Log::channel('import_fail')->info($data['email'] . ' Couldnot be stored . Has the validation message" : ' .  $validator->errors()->first());
        }
    }
    return redirect()->route('resellers')->with('success', 'Resellers imported successfully');

Even though I have csv_field in form, I get this error The csv_file field is required. It keeps the modal open.

Upvotes: 1

Views: 478

Answers (1)

Er Jagdish Patel
Er Jagdish Patel

Reputation: 193

I guess problem is here.

data: {
            csv_file: $('#csv_file').val(),
      },

You are sending text value i.e. name of file instead of actual file. and validating file.

Refer this to upload file using ajax. https://makitweb.com/how-to-upload-a-file-using-jquery-ajax-in-laravel-8/

Upvotes: 1

Related Questions