kennethjaysone's avatar

Unable to view image data upon posting a form

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());
    }

Here's the response for request->all(). I don't even see cover_photo

dd($request->all());

array:14 [
  "_token" => "nsiJLjvS6K2mFKpTpqQFFgYJRPWqVSeag68Lluce"
  "title" => "A beautiful apartment for sale"
]

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')); // returns null

I've ensured that i'm using the

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

Please help and thank you :)

0 likes
4 replies
kennethjaysone's avatar

Ok so i tried posting without ajax and i get this response

array:15 [▼
  "_token" => "nsiJLjvS6K2mFKpTpqQFFgYJRPWqVSeag68Lluce"
  "title" => "A beautiful apartment for sale"
  "cover_photo" => UploadedFile {#29 ▼
    -test: false
    -originalName: "house.jpg"
    -mimeType: "image/jpeg"
    -size: 54962
    -error: 0
  }
]
bestmomo's avatar

Are you sure you set this field in Ajax request ?

kennethjaysone's avatar

Here's my js @bestmomo

    $('#createAd[data-remote]').on('submit', function(e) {
    
        var form = $(this);
    
        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: form.serialize(),
            dataType: 'json',
            success: function(data) {
                console.log(data);
            },
            error: function(data) {
                var errors = data.responseJSON;
    
                if ($.isArray(errors)) {
                    $.each(errors, function(key, value) {
                        console.log(key + ' - ' + value);
                        $('#' + key).after('<div class="alert alert-danger">' + value + '</div>');
                    });
                }
    
            }
    
        });
    
    });

But apparently without ajax, i can post the data. Just wondering how to implement this with ajax.

Please or to participate in this conversation.