Home > Back-end >  How to access laravel validation error in Vue.js?
How to access laravel validation error in Vue.js?

Time:03-04

I'm using laravel 9 and Vue 3. I am trying to access laravel validation error in vue. Error message send by laravel.

{message: "The given data was invalid.",…}
errors: {supplyData.supplier_id: ["Please fill the supplier field"]}
supplyData.supplier_id: ["Please fill the supplier field"]
0: "Please fill the supplier field"
message: "The given data was invalid."

I have tried following code to access the error but it didn't work.

  <span
                    v-if="errors['supplyData.supplier_id']"
                   
                    
                    style="display:block; color:red;"
                    role="alert"
                >
                   {{ errors["supplyData.supplier_id"][0]}}
   </span>

api call

  create() {
        console.log(this.submitData);
        console.log(this.commonData);
        axios
            .post("/ajax/supply", {
                batchData: this.submitData,
                supplyData: this.commonData
            })
            .then(response => {
                if (response.data.success) {
                  //  console.log("success");
                    swal({
                        title: "Successfully created",
                        icon: "success"
                    }).then(() => {
                        window.location.href = "/supplies";
                    });
                    this.errors = {};
                }
            })
            .catch(error => {
                this.errors = error.response.data.error;
                 console.log(this.errors);
            });
    }

Controller:

  public function ajaxCreate(SupplyRequest $request){
    // return $request->all();
    $request->validate([
'supplier_id' => 'required',
]);

CodePudding user response:

If you check your console to see what is the real response from laravel backend, you probably see it is inside of data object,

Let's assume you have axios call like store()..

After this store request the data you got is response. The error is inside data of this response.

You can probably reach it like: response.data.errors

        .catch(error => {
            this.errors = error.response.data.errors; // this should be errors.
             console.log(this.errors);
        });
  • Related