Search code examples
laravelvue.jslaravel-5.3vue-resource

Laravel Validation with vue js


i want to post ajax request using vue-resource this.$http.post request. it worked perfectly fine if i passed all validation rules but i want to get some validations if it fails. so far i keep getting 500 error if i don't fill out some input fields. it's hard for me to debug the error because it didn't appeared on the network tab.

here's what i've done so far

//my modal component
<script>
export default {
    props: ['show'],

    data() {
        return {
            input: {
                id: '',
                name: '',
                address: '',
                email: ''
            },
            errorInputs: {}
        }
    },

    methods: {
        createStudent() {
            this.$http.post('/students', this.$data.input)
                .then((response) => {
               alert('added new row!)
            }, (response) => {
                console.log(response.data);
            });
        }
      }
   }
</script>

// my controller

public function store(Request $request) {
    $validator = $this->validate($request,[
        'id' => 'required',
        'name' => 'required|unique:students',
        'email' => 'required|unique:students|email',
        'address' => 'required',
    ]);

    if($validator->passes()){
        Student::create($request->all());

        return response()->json([], 201);
    }

    $errors = json_decode($validator->errors());

    return response()->json([
        'success' => false,
        'message' => $errors
    ],422);
}

any helps and references would be appreciated. i am using laravel 5.3 and vue js 2


Solution

  • $this->validate() returns 422 error response alongside your validation errors, so you should get those errors in then() second callback (like you do now). Your vue component body should be like this:

    {
        data() {
            // ...
        },
        createStudent() {
            this.$http
                .post('/students', this.input)
                .then(this.handleSuccess, this.handleError)
        },
        handleSuccess(res) {
            alert('student created')
        },
        handleError(res) {
            if (res.status === 422) {
                this.errorInputs = res.body
            } else {
                alert('Unkown error!')
            }
        }
    }
    

    Remember to add v-model="input.fieldName" properties to your inputs.