Jakša Mališić
Jakša Mališić

Reputation: 465

How to send an array of JSON objects to Laravel from Vue.js with AXIOS

So, my Laravel API endpoint would like to receive something like this to succesfully add it to DB:

{
  ICAO: 'ABC',
  name: 'The name of Airport',
  place: 'city',
  country: 'country'
}

I made parser which takes .csv file and parse it, and I want to send something like this with axios:

[
  {
    ICAO: 'ABC',
    name: 'The name of Airport',
    place: 'city',
    country: 'country'
  },
  {
    ICAO: 'DEF',
    name: 'The name of Airport',
    place: 'city',
    country: 'country'
  },
  {
    ICAO: 'GHI',
    name: 'The name of Airport',
    place: 'city',
    country: 'country'
  },
  {
    ICAO: 'JKL',
    name: 'The name of Airport',
    place: 'city',
    country: 'country'
  }
]

So I could iterate this array with foreach thus adding all objects within it to db.

  public function import(Request $request)
  {
    // Do validation
    $airports = $request->all();
    foreach ($airports as $airport) {
      Airport::create($airport)
    };

    return response('Airports imported', 200);
  }

I even tried sending one object with property 'data' which has value of aforementioned array of JSON objects and then tried to iterate over that prop.

It all works in postman, but when trying to send it with app, it doesn't work or it fills DB with empty rows.

I also use vuex store so my action for posting this is:

 importAirports (payload) {
  if (auth.roles('Operative')) {
    axios.post(api + '/airports/import?token=' + token, payload, { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
    .then(function (response) {
      console.log(response)
    })
    .catch(function (error) {
      commit('error', error)
      console.log(error)
    })
  }
}

Basic creation of one Airport works fine, as everything else but this doesn't. Any thoughts?

Upvotes: 0

Views: 4043

Answers (2)

maki10
maki10

Reputation: 561

You are sending Get method in Post request. In that way Laravel create you empty $request.

Try like this.

axios.post('your_route', {data: 'json_data_here"}, callback)

Upvotes: 0

Jamie Curnow
Jamie Curnow

Reputation: 794

I think your issue here may lie within the Vuex action. To my knowledge, a Vuex action's first parameter is the 'context' followed by a second parameter which is the payload. Your action params should look like this:

importAirports (context, payload) {
// do stuff
}

You can then use destructuring to get access to methods like commit, which I see you use in your .catch() block. Like this:

 importAirports ({ commit }, payload) {
  if (auth.roles('Operative')) {
    axios.post(api + '/airports/import?token=' + token, payload, { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
    .then(function (response) {
      console.log(response)
    })
    .catch(function (error) {
      commit('error', error)
      console.log(error)
    })
  }
}

Upvotes: 1

Related Questions