Unable to view image data upon posting a form

62 Views Asked by At

Problem: unable to see file image upload data. Getting null returned

Im trying to post an ad and i would like to see the data that i'm posting

So my form looks like so:

{!! Form::open(['data-remote', 'class' => 'form-vertical', 'route' => 'dashboard.ad.create', 'files' => true, 'id' => 'createAd']) !!}

            <div class="cover_photo">
                {!! Form::label('cover_photo', 'Cover Photo') !!}

                {!! Form::file('cover_photo') !!}
            </div>

{!! Form::close() !!}

This is the field with the issue, the file form field named cover_photo

My form request class has the following in the rules array

'cover_photo' => 'image',

I'm using ajax to post the form. All im doing in my controller is

public function postStoreAd(PostAnAddRequest $request) {
    dd($request->all());
}

The weird thing is i get all the other form fields data. Except for cover_photo In fact when i try to do the following i get null:

dd($request->file('cover_photo')); // return null

I've ensured that i'm using the

'files' => true, // In my Form::open()

Please help and thank you :)

1

There are 1 best solutions below

0
On

So in my jquery i have used data.serialize() which i found out won't work thanks to this article

Using this implementation Form, i was able to obtain the data i needed

var form = $(this);

var formdata = new FormData(form[0]); //form.serialize() wont work

form.find('div.alert').remove();

e.preventDefault();

var action = $(this).attr('action');

var method = $('input[name=_method]').val() || 'POST';

$.ajax({
    type: method,
    action: action,
    data: formdata, //form.serialize() wont work
    processData: false, // You need this
    contentType: false, // You need this
    dataType: 'json',
    success: function(data) {
        console.log(data);
    },
    error: function(data) {
        var errors = data.responseJSON;

        $.each(errors, function(key, value) {
            console.log(key + ' - ' + value);
            $('#' + key).after('<div class="alert alert-danger">' + value + '</div>');
        });

    }

});