Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting a 422 error code?

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',
        // ...
    ]);

    // ...
}
like image 793
Donnie Avatar asked May 10 '16 18:05

Donnie


People also ask

How do I fix Error 422?

Broadly speaking, if you see an HTTP 422 error it means the server understands your request, but it can't fulfill it due to a problem on your end. If you fix that problem, you should be able to reload the page and the error will go away.

When should 422 be used?

A 422 status code occurs when a request is well-formed, however, due to semantic errors it is unable to be processed. This HTTP status was introduced in RFC 4918 and is more specifically geared toward HTTP extensions for Web Distributed Authoring and Versioning (WebDAV).

What are HTTP status codes?

An HTTP status code is a message a website's server sends to the browser to indicate whether or not that request can be fulfilled. Status codes specs are set by the W3C. Status codes are embedded in the HTTP header of a page to tell the browser the result of its request.


1 Answers

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: '[email protected]',
    numberOfOffices: 1,
    numberOfEmployees: 2,
  }
}
like image 192
Brandon Anzaldi Avatar answered Sep 28 '22 13:09

Brandon Anzaldi