shieldcy
shieldcy

Reputation: 602

Pass form data and a parameter with Vue axios to Laravel controller

I am trying to send a file input AND one more parameter to the controller in order to upload the files.

For image / file upload I use the "vue-upload-multiple-image" plugin.

            <vue-upload-multiple-image
              dragText="Drop your photos here"
              browseText="(or click to upload)"
              primaryText="Default"
              markIsPrimaryText="Set as default"
              popupText="This photo will be displayed as default"
              @upload-success="uploadImageSuccess"
              @before-remove="beforeRemove"
              />

In Vue methods:

 uploadImageSuccess(formData, index, fileList) {
  const config = {
    headers: {
      'content-type': 'multipart/form-data',
    }
  }

  this.$store.dispatch('listings/addPhotos', {
    'imageData': formData,
    'config': config
  })
},

In vuex store I have the following:

  async addPhotos ({ commit }, listing) {
    await axios.post('/api/addPhotos', listing.imageData, listing.config)
      .then((res) => {
        console.log(res.data)
      }).catch((err) => {
        console.log(err)
      })
  },

And in Laravel controller:

public function addPhotos(Request $request)
  {
      $imgpath = public_path('images');
      $fileName = $request->file->getClientOriginalName();
      $newName = time() . '_'.$fileName.'.' . $request->file->getClientOriginalExtension();
      $request->file->move($imgpath, $newName);

      $post['name'] = $file_name;
      //$post['paired'] = 'slug';
      //$post['listing_id'] = 0;
      $result = ListingPhoto::insertGetId($post);
  }

This works fine. Image file is uploaded and data are also uploaded in DB.

What I can't figure out is how to use another parameter so that I can add some data in the field "paired" in database.

Lets say now I send "formData". Is it possible to send formData AND slug?

Something like this:

this.$store.dispatch('listings/addPhotos', {
    'imageData': formData,
    'slug': slug,
    'config': config
  })

Or maybe adding it into the formdata like this:

let formDataN = new FormData();
formDataN.append('imgfile', formData);
formDataN.append('slug', slug);

I tried both ways but it returns an error. When I send the "formDataN" (which contains the normal formData with the image AND the slug) it stops working. When I try for example to getClientOriginalName, it either says "Call to a member function getClientOriginalName() on null" or "Trying to get property 'file' of non-object"

Can anyone help me with this? Any suggestions of how to do this? I just want to use the formData as I normally do BUT also send another parameter "slug" to add in the database table.


EDIT: I found a way of doing this but I feel this is not the best solution. Anyway, for anyone interested:

uploadImageSuccess(formData, index, fileList) {
  const config = {
    headers: {
      'content-type': 'multipart/form-data',
    }
  }

  let slug = 'slug-uid-'+this.user.id

  this.$store.dispatch('listings/addPhotos', {
    'imageData': formData,
    'slug': slug,
    'config': config
  })
},

in vuex store:

  async addPhotos ({ commit }, listing) {
    await axios.post(`/api/addPhotos/${listing.slug}`, listing.imageData, listing.config)
      .then((res) => {
        console.log(res.data)
      }).catch((err) => {
        console.log(err)
      })
  },

in API call:

Route::post('addPhotos/{slug}', 'ListingController@addPhotos');

And in the controller:

public function addPhotos($slug, Request $request)
  {
    ...

EDIT2: I just realised the vue upload image plugin I am using, it already creates a "formData" so I didn't have to create a new one in my Vue code. So what I need to do is to just append any other parameter I want. Final solution:

uploadImageSuccess(formData, index, fileList) {    
  let slug = 'slug-uid-'+this.user.id
  formData.append("slug", slug);

  this.$store.dispatch('listings/addPhotos', formData)
},

In order to retrieve the actual image file, you use "file" (this is how it is defined in the vue-upload-multiple-image plugin). In laravel controller:

$request->file('file')->getClientOriginalName();
$request->slug;

Upvotes: 0

Views: 4069

Answers (1)

Mohammad Salim Hosen
Mohammad Salim Hosen

Reputation: 303

Try this if it helps

Rather sending formdata and slug to vuex attach slug to formData like that

var formData = new FormData();
formData.append("image", image); // this should be your image
formData.append("slug", slug); // it is the slug

this.$store.dispatch('listings/addPhotos', formData)

In vuex:

  async addPhotos ({ commit }, formData) {
    await axios.post('/api/addPhotos', formData, {'content-type': 'multipart/form-data'})
      .then((res) => {
        console.log(res.data)
      }).catch((err) => {
        console.log(err)
      })
  },

In Laravel:

public function addPhotos(Request $request)
  {
      $img = $request->file('image');
      $slug = $request->slug;
  }

Upvotes: 1

Related Questions