Vee Validate show errors by REST API server messages Laravel + Vue.js

Last Updated: May 13, 2020

In your Laravel + Vue Application, you have to do two validations to make error-free application

  • 1 Client side validation
  • 2 Server side validation

We are using popular Vee Validate Vue.js package for the client-side validation.

In this article, I am going to show you how you can do the server-side validation and show the error message in your Vue.js code.

Laravel is our backend, and I am going to create a new user by calling Rest API endpoint /api/user.

This endpoint will execute the following located in your UserController.php file.

   public function create(Request $request)
    {
        $messages = [
            'firstname.required' => 'First Name is required',
        ];
       $validator = Validator::make($request->all(), [
            'email' => 'required|unique:users|max:255',
            'firstname' => 'bail|required',
            'lastname' => 'bail|required',
        ],$messages);



        if ($validator->fails()) {

            return $this->respondWithError($validator->messages()->all(),Response::HTTP_UNPROCESSABLE_ENTITY);
            //return $validatedData->errors->toJson();
        }


        // if no errors you can create the user
}

You can see that I am validating two things here.
1 Checking the email is already exists in users table
2 Fist name is required

If I send the post request from my Vue.js application I should receive the error message to my catch block of the axios promise

.catch(error => {
    this.$validator.errors.add({field:'email',msg:error.response.data.errors.email[0]});
    this.$validator.errors.add({field:'firstname',msg:error.response.data.errors.firstname[0]});

});

Important
You have to add the following code to your Vue complement to make this work otherwise you can not see this error messages

export default {
      $_veeValidate: {
	validator: 'new'
     },

     // other code

}