0
votes

I'm trying to output all Laravel errors using vue. I'm getting the output, but I don't know how to format the output.

Vue Component

        data() {
          return {
              status: '',
              submitted: false,
              message: '',
              name: '',
              description: '',
              errors: null,
           }
        },

        //This axios request is wrapped into the same component
        axios({
                method: 'POST',
                url: '/',
                data: {
                    name: this.name,
                    description: this.description
                }
            }).then(function (response) {

               //Clears form submit fields
                this.clearValues();
                this.message = response;   

            }.bind(this))
            .catch(error => {
                    error => this.status = error.response.data.status;
                    this.errors = error.response.data.errors;
                    console.log(error.response.data.errors);
            });
        }

Vue Components Template

<ul v-for="(error, index) in errors">
   <li>{{error}}</li>   
</ul>

The JSON Output In Console

{
  description: [ "The description field is required." ],
  name: [ "The name field is required." ]
}

Chrome Output

  • [ "The name field is required." ]
  • [ "The description field is required." ]

I'd essentially like to output all errors. Example:

  • Name error 1
  • Name error 2
  • Description error 1
  • Description error 2

const app = new Vue({
  el: '#app',

  data:{
    errors: {
      description: [ "The description field is required." , "Another error"],
      name: [ "The name field is required." ],
    }
  }

});

Edit here is a snippet example:
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17-beta.0/vue.js"></script>

<div id="app">
  <ul v-for="(error, key) in errors">
   <li v-text="error[0]" ></li>   
  </ul>
</div>
2

2 Answers

1
votes

If you want to extract "The name field is required" from ["The name field is required"], in theory, you should use index 0:

<ul v-for="(error, key) in errors">
   <li v-text="key" ></li>
   <li v-text="error[0]" ></li>   
</ul>

or better:

<div v-for="(error,key) in errors" >
    <ul v-for="value in error" >
        <li v-text="key+': '+value" ></li>
    </ul>
</div>
0
votes

Since the error is an object, your VUE component will be like this:

<ul v-for="(error, key) in errors">
   <li>{{key}}</li>
   <li>{{error}}</li>   
</ul>

It will output like:

  • Name error 1
  • Description error 1
  • Name error 2
  • Description error 2