1

I have some complex data and I want to show the validation error array data in vue file but I can not do it because I have got some data that has an index and showing like contacts.0.name: ["...."].

Please share your opinion how I can show the error.

vue file

<template>
  <div>
    <form enctype="multipart/form-data" @submit.prevent="handleSubmit">
      <div v-for="(contact, index) in contacts" :key="index" class="row">
        <div class="col col-md-3">
          <div class="form-group mb-4">
            <label for="personName">Contact Person Name</label>
            <input
              id="personName"
              v-model="contact.name"
              type="text"
              class="form-control"
            />
            <small> Want to show here the error ? </small
            >
          </div>
        </div>

        <!-- Add or Remove button -->

        <div class="col col-md-12 text-right">
          <div class="row ml-4">
            <div v-show="index == contacts.length - 1">
              <button
                class="btn btn-warning mb-2 mr-2 btn-rounded"
                @click.prevent="add"
              >
                Add More
              </button>
            </div>
            <div v-show="index || (!index && contacts.length > 1)">
              <button
                class="btn btn-danger mb-2 mr-2 btn-rounded"
                @click.prevent="remove"
              >
                Remove
              </button>
            </div>
          </div>
        </div>
      </div>
    </form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      contacts: [
        {
          name: "",
        },
      ],

      errors: [],
    };
  },
  methods: {
    handleSubmit() {
      let data = new FormData();
      data.append("contacts", JSON.stringify(this.contacts));

      Request.POST_REQ(data, "/add-institute")
        .then(() => {
          alert("success");
        })
        .catch((err) => {
          this.errors = err.response.data.errors;
        });
    },
    add() {
      this.contacts.push({
        name: "",
        email: "",
        phone: "",
        alternate_phone: "",
      });
    },
    remove(index) {
      this.contacts.splice(index, 1);
    },
  },
};
</script>

controller file


public function add_institute(Request $request) {
  $request['contacts'] = json_decode($request['contacts'], true);
  $request->validate([
      'contacts.*.name'=> 'unique:institute_contact_people|distinct',
  ]);

  ...rest of code of insert 

  return response()->json("Success...");
}

Getting Error Response data

errors: {
  contacts.0.name: ["The contacts.0.name has already been taken.", "The contacts.0.name field has a duplicate value."]
  0: "The contacts.0.name has already been taken."
  contacts.1.name: ["The contacts.1.name has already been taken.", "The contacts.1.name field has a duplicate value."]
  0: "The contacts.1.name has already been taken."
}
5
  • This seems to be doable but damn, can you change the error object into something more friendly and valid JSON ? Either have only an array with indexes or a nested object with contact > [id] > errorName ? Will be far more easier for you to handle. Commented Mar 26, 2021 at 11:13
  • Also, is this question aimed towards laravel, laravel-5 or laravel-7 ? If it fit into all of the 3, just keep laravel. Commented Mar 26, 2021 at 11:19
  • prntscr.com/10w1289 Commented Mar 26, 2021 at 11:26
  • Please accept my answer if it helped somehow. :) Commented Mar 28, 2021 at 19:16
  • Hi, @kissu I appreciate your answer but It's not solved for me I have done a different code. But If you are sure your code will solve others problem then I will vote for it no problem Commented Mar 29, 2021 at 14:51

2 Answers 2

1

Okay, so your error data is basically an object with array of errors in it. Pretty much like this

errors: {
  'contacts.0.name': [
    'The contacts.0.name has already been taken.',
    'The contacts.0.name field has a duplicate value.',
  ],
  'contacts.1.name': [
    'The contacts.1.name has already been taken.',
    'The contacts.1.name field has a duplicate value.',
  ],
},

For me, it will be better if you could achieve something like this as an error response (an array of objects with errors array in it)

betterErrors: [
  {
    location: 'contact.0.name',
    errors: [
      'The contacts.0.name has already been taken.',
      'The contacts.0.name field has a duplicate value.',
    ],
  },
  {
    location: 'contact.1.name',
    errors: [
      'The contacts.1.name has already been taken.',
      'The contacts.1.name field has a duplicate value.',
    ],
  },
],

For me, as of right now, it feels wrong but you can achieve a display of your errors with something like this

<template>
  <div>
    <div v-for="(error, key) in errors" :key="key">
      <hr />
      <span v-for="(errorItem, innerKey) in error" :key="innerKey" style="margin-top: 2rem">
        {{ errorItem }}
      </span>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      errors: {
        'contacts.0.name': [
          'The contacts.0.name has already been taken.',
          'The contacts.0.name field has a duplicate value.',
        ],
        'contacts.1.name': [
          'The contacts.1.name has already been taken.',
          'The contacts.1.name field has a duplicate value.',
        ],
      },
    }
  },
}
</script>

PS: having a :key with an array looping index is really bad tbh. That's why I do recommend a location field in your error response.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your reply it's really glad that you respond to me. I can understand to see the answer but how I could achieve the JSON format which u suggest because the Laravel validation gives me the error. plz check the below screenshot prntscr.com/10w1w10
Finally, I have solve the problem to follow Object-Oriented Form laracasts.com/series/learn-vue-2-step-by-step/episodes/19 Thanks to The Community
1

in your controller


 $request->validate([
        'ClinicName' => 'required|string|min:200',
        'Branches.*.BranchName'=>'required|string|min:200'
    ]);

in your vue3 file, to access the errors which will have keys such as, 'Branches.0.BranchName' then you can access the above error with for loop similar to this


<p v-if="form.errors['Branches.' + counter + '.BranchName']"
   class="mt-2 text-sm text-red-600 dark:text-red-500">
              {{ form.errors["Branches." + counter + ".BranchName"] }}
 </p>

here the counter can be any counter starting from 0.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.