How Set Errors From Laravel In Vuejs
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
This is the error message from laravel
how do set this.errors with error message from laravel
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
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS - Conditionally Load a Different Page
- → Make a Laravel collection into angular array (octobercms)
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?
- → Validating fileupload(image Dimensions) in Backend Octobercms
- → OctoberCMS Fileupload completely destroys my backend
- → How do I call the value from another backed page form and use it on a component in OctoberCms