15

I am making a POST request, but unable to get anything besides a 422 response.

Vue.js client code:

new Vue({
  el: '#app',

  data: {
    form: {
      companyName: '',
      street: '',
      city: '',
      state: '',
      zip: '',
      contactName: '',
      phone: '',
      email: '',
      numberOfOffices: 0,
      numberOfEmployees: 0,
    }
  },

  methods: {
    register: function() {
      this.$http.post('/office-depot-register', this.form).then(function (response) {

        // success callback
        console.log(response);

      }, function (response) {

        // error callback
        console.log(response);

      });
    }
  }
});

Laravel Routes:

Route::post('/office-depot-register', ['uses' => 'OfficeDepotController@register', 'as' => 'office-depot-register']);

Laravel Controller:

public function register(Request $request)
{
    $this->validate($request, [
        'companyName' => 'required',
        // ...
    ]);

    // ...
}
Donnie
  • 6,229
  • 8
  • 35
  • 53
  • 2
    From what I can tell, Laravel sending back a 422 means that the request didn't fulfill validation requirements. (E.g. Missing required field, other validation failures) http://stackoverflow.com/questions/34966690/error-422-unprocessable-entity-in-laravel-with-ajax Since you have `companyName` required, but have it as an empty string, that could well be what's causing your issue. – Brandon Anzaldi May 10 '16 at 18:48
  • 1
    That's exactly it. Leave your comment as an answer and I'll accept it. – Donnie May 10 '16 at 18:54
  • Glad I was able to help :) – Brandon Anzaldi May 10 '16 at 19:03

1 Answers1

20

Laravel allows you to define certain validations on fields it accepts. If you fail these validations, it will return HTTP 422 - Unprocessable Entity. In your particular case, it appears that you're failing your own validation tests with an empty skeleton object, since companyName is required, and an empty string does not pass the required validation.

Assuming the other fields are similarly validated, a populated data object should solve your issue.

data: {
  form: {
    companyName: 'Dummy Company',
    street: '123 Example Street',
    city: 'Example',
    state: 'CA',
    zip: '90210',
    contactName: 'John Smith',
    phone: '310-555-0149',
    email: 'john@example.com',
    numberOfOffices: 1,
    numberOfEmployees: 2,
  }
}
Brandon Anzaldi
  • 6,884
  • 3
  • 36
  • 55