Ad

How Set Errors From Laravel In Vuejs

- 1 answer

I am trying to retrieve errors from Laravel in Vue, but i get this error message in my console "Cannot set property 'errors' of undefined". I have tried different approaches like direct assignment of errors and the $set() of vue to set error message to the error object of my data function, but it is still in vain.

This is my code

 export default{

  data(){
    return{
        form: {},
        errors:{}
    }
 },
 methods:{
      async onSave() {
        await Api().post('/stocks/store',this.form)
        .then()
        .catch(function (error) {
           if(error.response && error.response.status == 422) {
              let errors = error.response.data.errors;
              // this.$set(this.$data.errors,'errors',errors)
              console.log(errors);
              this.errors = errors;
           }
        });  
  }
}

This is how the error message from my console

enter image description here

This is the error message from laravel

enter image description here

how do set this.errors with error message from laravel

Ad

Answer

If you look closely at the error, it says

Cannot set property 'errors' of undefined

So the problem is you are trying to set a property of an undefined object, in this case: this, your Vue component.

An easy and convenient way to solve this problem is to use arrow function instead of a regular function in your Promise.catch() callback. To put simply, a regular function expression has his own this context, where arrow function does not.

Here is a sample of code that should help you understand better:

        new Promise().then()
        .catch((error) => {
           if(error.response && error.response.status == 422) {
              this.errors = error.response.data.errors;
           }
        });  

To learn more about arrow function and the binding of this

Ad
source: stackoverflow.com
Ad