dimanche 13 octobre 2019

Vuejs how to display laravel input array validation errors

I am having trouble showing error messages in my vue component that are retrieved my my Laravel app.

This is the response in the network tab

{message: "The given data was invalid.",…}
errors: {results.0.winner: ["This field is required"], results.1.winner: ["This field is required"],…}
results.0.winner: ["This field is required"]
results.1.winner: ["This field is required"]
results.2.winner: ["This field is required"]
message: "The given data was invalid."

And this is the error in console

admin.js:59648 [Vue warn]: Error in render: "TypeError: Cannot read property '0' of undefined"

This is my component

<template>
    <form @submit.prevent="submit" class="mb-5">
        <div class="row">
            <div v-for="(setting, index) in settings">
                <div class="card">
                    <div class="card-body">
                        <div class="form-group">
                            <input type="text" class="form-control" v-model="setting.number">
                            <div v-if="errors && errors.results[index].winner" class="text-danger"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="form-group row">
            <div class="col-sm-8">
                <button type="submit" class="btn btn-primary">
                    Save Results
                </button>
            </div>
        </div>
    </form>
</template>
<script>

export default {
    props: {
        settings: {
            type: Array,
            default: () => []
        },
    },
    data: function() {
        return {
            errors: {},
        }
    },
    mounted() {

    },
    methods: {
        submit: function() {
            let results = [];

            this.settings.forEach(function(item) {
                results.push({
                    prize: item.prize,
                    winner: item.number
                });
            });

            axios.post('save', {results: results}).then(response => {
                if(response.status === 200) {
                    //window.location.href = '/admin/lottery'
                }
            }).catch(error => {
                if (error.response.status === 422) {
                     this.errors = error.response.data.errors || {}
                }
            });
        },
    },
};
</script>

and if it helps my laravel function

public function store(Request $request)
{
    $request->validate([
        'results.*.winner'  => 'required|gt:0',
    ],
    [
        'results.*.winner.required' => 'This field is required',
    ]);
}


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/33r3ikT
via IFTTT

Aucun commentaire:

Enregistrer un commentaire